Excel 2013 VBA数据库连接

时间:2018-05-29 09:26:09

标签: sql excel vba

我在Excel 2013上遇到VBA问题。

我问一个参数,而不是为SQL创建一个键,但是如果我尝试使用它,如果我留下字符串.Refresh BackgroundQuery:=False我得到一个

  

1004运行时错误

如果我剪掉它,转移不起作用......有什么建议吗?

我写了这段代码:

Bolla = InputBox("Numero Bolla?", "bolla", " ", 3000, 5000)

CHIAVE = "CCI " & bolla

Sheets.Add
    ActiveSheet.Name = ("Trasferimento")

 With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
        "ODBC;DSN=CCI_DATV3;", Destination:=Range("$A$1")).QueryTable
        '.CommandType = 0
        .CommandText = Array( _
        "SELECT §FIEB01L.NUDOS, §FIEB01L.RASCS, §FIEB01L.DASPS, §FIEB01L.DESTS, §FIEB01L.DEFIS, §FIEB01L.DESCS, §FIEB01L.QTISS, §FIEB01L.COSTS, §FIEB01L.BOBIS, §FIEB01L.TESIS, §FIEB01L.TESES, §FIEB01L.ORPRS FR" _
        , "OM CCI_DATV3.§FIEB01L WHERE ((§FIEB01L.NUDOS=" & CHIAVE & "))")
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .BackgroundQuery = True
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .PreserveColumnInfo = True
    .ListObject.DisplayName = "Tabella_Query_da_CCI_DATV3"
    .Refresh BackgroundQuery:=False
End With

1 个答案:

答案 0 :(得分:0)

我认为问题可能出在.CommandText属性中。尝试将其设置为:

.CommandText = "SELECT §FIEB01L.NUDOS, §FIEB01L.RASCS, §FIEB01L.DASPS, §FIEB01L.DESTS, §FIEB01L.DEFIS, §FIEB01L.DESCS, §FIEB01L.QTISS, §FIEB01L.COSTS, §FIEB01L.BOBIS, §FIEB01L.TESIS, §FIEB01L.TESES, §FIEB01L.ORPRS FROM CCI_DATV3.§FIEB01L WHERE §FIEB01L.NUDOS ='" & CHIAVE & "'"

我只是删除了Array()函数,删除了换行符后的逗号和查询中的额外括号。鉴于CHIAVE是一个字符串,撇号也被添加到查询中。

此外,.CommandType应设置为xlCmdSql

如果有帮助,请告诉我