我正在尝试使用SQL在Excel中查询表(Purchases)。但是,运行以下脚本时出现错误。
tableaddress变量产生购买!$ A $ 2:$ F $ 1200这是表格的范围"购买"。
生成的SQL查询是:
Select * From [Purchases!$A$2:$F$1200]
当前的VBA本身如下所示:
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strSQL As String
Dim tableAddress As String
Set cn = New ADODB.Connection
cn.ConnectionString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" & ActiveWorkbook.Path & Application.PathSeparator & ActiveWorkbook.Name
cn.Open
tableAddress = "Purchases!" & Range("Purchases").Address
strSQL = "Select * From [" & tableAddress & "]"
rs.Open strSQL, cn
cn.Close
但是,执行时我得到以下错误...
[Microsoft][ODBC Excel Driver] 'Purchases!$A$2:$F$1200' is not a valid name.
Make sure that it does not include invalid characters or punctuation and that it is no too long.
我在错误中看到了撇号,但我不确定是否会引用标点符号或如何删除它。
谢谢!
答案 0 :(得分:1)
以下代码应该有效:
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strSQL As String
Dim tableAddress As String
Set cn = New ADODB.Connection
cn.ConnectionString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" & ActiveWorkbook.Path & Application.PathSeparator & ActiveWorkbook.Name
cn.Open
tableAddress = "Purchases$" & Range("Purchases").Address(False, False)
strSQL = "Select * From [" & tableAddress & "]"
rs.Open strSQL, cn
cn.Close