我有一个宏来查询SQL数据到多个工作表,我遇到的问题是我想允许代码从单元格值引用SQL服务器地址和数据库名称(即用户输入他们想要的服务器/数据库)连接和提取数据
具有固定服务器/数据库名称(SQLEXPRESS / Datalogger)的当前代码是:
ActiveWorkbook.Queries.Add Name:="DataTable", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Sql.Database("".\SQLEXPRESS"", ""Datalogger"")," & Chr(13) & "" & Chr(10) & " dbo_DataTable = Source{[Schema=""dbo"",Item=""DataTable""]}[Data]" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " dbo_DataTable"
Sheets.Add.Name = "DataTable"
Sheets("DataTable").Move After:=Sheets("HOME")
用户可以指定服务器/数据库名称的区域将位于单元格B1和B2。所以我尝试将以下代码添加为字符串,但它不起作用:
Dim sSqlSvr As String
Dim sSqlDb As String
sSqlSvr = Worksheets("HOME").Range("B1")
sSqlDb = Worksheets("HOME").Range("B2")
ActiveWorkbook.Queries.Add Name:="DataTable", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Sql.Database(sSqlSvr, sSqlDb)," & Chr(13) & "" & Chr(10) & " dbo_DataTable = Source{[Schema=""dbo"",Item=""DataTable""]}[Data]" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " dbo_DataTable"
Sheets.Add.Name = "DataTable"
Sheets("DataTable").Move After:=Sheets("HOME")
我假设我在调用字符串时遗漏了一些东西。错误是运行时错误' 1004'。 "无法从数据模型中获取数据"。 "导入sSqlSvr不匹配导出。你错过了模块参考吗?"
我猜它的字面意思是用sSqlSvr / sSqlDb查找服务器/ db名称而不是识别为字符串......有什么建议吗?
答案 0 :(得分:1)
您在字符串中将变量名称作为文字。您需要从字符串中转义以将变量的值插入到字符串中:
ActiveWorkbook.Queries.Add Name:="DataTable", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Sql.Database(""" & sSqlSvr & """, """ & sSqlDb & """)," & Chr(13) & "" & Chr(10) & " dbo_DataTable = Source{[Schema=""dbo"",Item=""DataTable""]}[Data]" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " dbo_DataTable"
修改:固定双引号!