I have a macro to query SQL data into multiple sheets, and the problem I encounter is that I want to allow the code to reference the SQL server address and database name from cell values (i.e. User inputs which server/database they want to connect and pull data from)
The current code with a fixed server/db name (SQLEXPRESS/Datalogger) is:
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")
The area where the user can specify the server/db name would be in cells B1 & B2. So I tried the following code to add as a string, but it's not working:
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")
I'm assuming I'm missing something here in calling the string. The error is Run-time error '1004'. "Couldn't get data from the Data Model". "The import sSqlSvr matches no exports. Did you miss a module reference?"
I guess the its literally looking for a server/db name with sSqlSvr/sSqlDb instead of recognizing as a string... any suggestions?