我在尝试通过查询导入访问数据库时遇到问题,但使用变量变量是 macroWB 和 cust macroWB 指的是文件路径 cust 指的是选定的客户名称 VBA 代码适用于固定值 如果有更专业(更快)的方法,请告知
On Error Resume Next
Sheets("db").Delete
On Error GoTo 0
Dim pq As Object
For Each pq In ThisWorkbook.Queries
pq.Delete
Next
Dim macroWB As String
macroWB = ThisWorkbook.Path
cust = Sheets("pre-filter").Range("C5").Value
ActiveWorkbook.Queries.Add Name:="customers Materials", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Access.Database(File.Contents(macroWB & ""\Database2.accdb""), [CreateNavigationProperties=true])," & Chr(13) & "" & Chr(10) & " #""_customers Materials"" = Source{[Schema="""",Item=""customers Materials""]}[Data]," & Chr(13) & "" & Chr(10) & " #""Filtered Rows"" = Table.SelectRows(#""_customers Materials"", each ([Cutomername] = cust))" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Filtered Rows"""
Sheets.Add After:=ActiveSheet
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""customers Materials"";Extended Properties=""""" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array("SELECT * FROM [customers Materials]")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = False
.ListObject.DisplayName = "customers_Materials"
.Refresh BackgroundQuery:=False
End With
Selection.ListObject.QueryTable.Refresh BackgroundQuery:=False
Range("customers_Materials[[#Headers],[Cutomername]]").Select
ActiveSheet.Name = "db"