クエリを介してアクセス データベースをインポートしようとすると問題が発生しますが、変数を使用すると、変数は 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"