【问题标题】:SQL Statement in VBA can not recognize my excel worksheetVBA 中的 SQL 语句无法识别我的 Excel 工作表
【发布时间】:2020-12-14 21:51:45
【问题描述】:

错误:无效的对象名称“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

【问题讨论】:

  • 如果你的表名是Tabelle1,为什么还要写Tabelle1$
  • 对不起,工作表名称是 Tabelle1$,而不是 Tabelle1。
  • 我认为“$”是一个无效字符,所以请删除它(至少它似乎是我的语言)
  • 我改变了它,但不幸的是它对我没有用..
  • 您是否仍然收到带有新名称的“无效对象名称...”

标签: sql excel vba import-from-excel data-import


【解决方案1】:

有什么对我有用:

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

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

【讨论】:

    猜你喜欢
    • 2021-07-14
    • 2016-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多