VBA 在将单元格值提取到 SQL 查询中时抛出错误

VBA throws an error when picking up cell values into SQL query

从某些单元格中为我的 SQL 提取值时出现以下错误。但是,当我将值硬编码到代码中时,它工作正常。所以,这显然与我编写它的语法有关。

出于多种原因,我正在寻找动态,希望有人能帮助我。

错误:Microsoft Access 数据库引擎找不到对象“objectname”

值被硬编码的工作代码:

mySQL = "SELECT * FROM [listname];"
With cnt
.ConnectionString = _
"Provider=Microsoft.ACE.OLEDB.12.0;WSS;IMEX=0;RetrieveIds=Yes;DATABASE=https://sharepoint.com/sites1/xx/;LIST= {0C3G7BTF-000E-4C16-8E07-E4B7F525069F};"
.Open
End With

无效代码:

mySQL = "SELECT * FROM ['" & Sheet3.Range("c1") & "'];"
With cnt
.ConnectionString = _
"Provider=Microsoft.ACE.OLEDB.12.0;WSS;IMEX=0;RetrieveIds=Yes;DATABASE=https://sharepoint.com/sites1/xx/;LIST= {'" & Sheet3.Range("d1") & "'};"
.Open
End With

我建议将您的连接字符串值放在一个变量中,然后打印它(例如 debug.print myConnectionString)以执行每个字符比较的字符。

此外,您对 sheet.range("d1")

的引用用单引号引起来
"Provider=Microsoft.ACE.OLEDB.12.0;WSS;IMEX=0;RetrieveIds=Yes;DATABASE=https://sharepoint.com/sites1/xx/;LIST= {'" & Sheet3.Range("d1") & "'};"

也许这些是导致您出现问题的原因。您似乎在 mySQL 变量赋值中遇到了同样的问题。

编辑:

也许这可行:

mySQL = "SELECT * FROM [" & Sheet3.Range("c1") & "];"
myConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;WSS;IMEX=0;RetrieveIds=Yes;DATABASE=https://sharepoint.com/sites1/xx/;LIST= {" & Sheet3.Range("d1") & "};"
debug.print myConnectionString
'Open execution window (ctrl g) to get the value of myConnectionString

With cnt
.ConnectionString = myConnectionString
.Open
End With