下面的代碼來自Excel 2016中從SQL Server Express數據庫導入數據期間記錄的宏。如何在記錄的Excel-VBA代碼中插入可變數據庫名稱?
Sub Macro2()
ActiveWorkbook.Queries.Add Name:="Query1", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Sql.Database(""DESKTOP\SQLEXPRESS"", ""2014-All-1"", [Query=""SELECT *#(lf) FROM [2014-All-1].[dbo].[OtherData]#(lf)#(lf) WHERE volume > 1""])" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " Source"
Sheets.Add After:=ActiveSheet
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Query1" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array("SELECT * FROM [Query1]")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Query1"
.Refresh BackgroundQuery:=False
End With
Selection.ListObject.QueryTable.Refresh BackgroundQuery:=False
End Sub
我試圖讓數據庫名稱的變量,通過增加變量MyDB
,這是在代碼的長行使用了兩次,你可以看到。最初這是數據庫的名稱:2014-All-1
不幸的是,這種方法不起作用。有人知道我可以用變量名替換數據庫嗎?
Sub Macro2()
MyDB = "2014-All-1"
ActiveWorkbook.Queries.Add Name:="Query1", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Sql.Database(""DESKTOP\SQLEXPRESS"", ""MyDB"", [Query=""SELECT *#(lf) FROM [MyDB].[dbo].[OtherData]#(lf)#(lf) WHERE volume > 1 ""])" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " Source"
Sheets.Add After:=ActiveSheet
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Query1" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array("SELECT * FROM [Query1]")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Query1"
.Refresh BackgroundQuery:=False
End With
Selection.ListObject.QueryTable.Refresh BackgroundQuery:=False
End Sub
你好史蒂夫,非常感謝這個優雅的結構代碼部分!它工作完美!最好的問候,馬塞爾 – user2165379
不用擔心,很高興有幫助。我討厭所有那些用引號括起來的東西,所以當這種事情出現時,我經常使用'Replace'替代它,而不是試圖使用串聯來構建字符串。我認爲它也容易閱讀。 –
是的,我會在下次有類似的情況時記住這一點。 – user2165379