VBA中的SQL语句无法识别我的Excel工作表

问题描述

错误:无效的对象名称'Tabelle1 $'

我正在尝试将Tabelle1作为工作表引用。 由于我是vba的新手,所以我不明白为什么脚本无法识别它,或者我必须做什么才能使其识别。

感谢您的帮助。

Sub WriteDataIntosqlTable()

Dim cn                    As Object
Dim strQuery              As String

Set cn = CreateObject("ADODB.Connection")
strQuery = "[dbo].[MyTable]"

 With cn
     .Provider = "sqloledb"
     .ConnectionString = "Data Source=myserver;Initial Catalog=mydatabase;Integrated Security=sspI;"
     .Open
End With


  
s = "INSERT INTO [ODBC;Driver=sqlOLEDB;Data Source=myserver;Initial Catalog=mydatabase;Integrated Security=sspI;Trusted_Connection=Yes].strQuery( ldf_nr,datum,abteilung_na,positions_nr,positions_na,ma_nr,ma_na,ma_plan_beginn,ma_plan_ende,ma_plan_pause,ma_plan_dauer_netto  ) " _
& "SELECT  a.Col1,a.Col2,a.Col3,a.Col4,a.Col5,a.Col6,a.Col7,a.Col8,a.Col9,a.Col10,a.Col11 " _
& "FROM [Tabelle1$] as a" _
& "LEFT JOIN [ODBC;Driver=sqlOLEDB;Data Source=myserver;Initial Catalog=mydatabase;Integrated Security=sspI;Trusted_Connection=Yes].strQuery as b ON a.Col1 = b.[ldf_nr]" _
& "WHERE b.[ldf_nr] Is Null"
cn.Execute s
cn.Close
    Set cn = nothing
End Sub

解决方法

有什么对我有用:

With Worksheets("Tabelle1").ListObjects.Add(SourceType:=0,Source:="ODBC;DRIVER=SQL Server;SERVER=*SERVER ADRESS*;UID=*ID*;PWD=*PASSWORD*;APP=Microsoft Office 2010;WSID=*PC NAME*;DATABASE=*DATABASENAME*",Destination:=Worksheets("Tabelle1").Range("$A$1")).QueryTable
        .CommandText = Array("*SQL String Query*")
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .PreserveColumnInfo = True
        .ListObject.DisplayName = "Tabelle1"
        .Refresh BackgroundQuery:=False
    End With

您需要用数据替换“ *”之间的内容,以使其正常工作。