(Solved) – How to turn a query name into variable

(solved)-–-how-to-turn-a-query-name-into-variable

i need to make repitative queries, but I’ve really stuck on queries names and have to change’em manually every time, like Name_1, Name_2 etc. The orignal code looks like this:

ActiveWorkbook.Queries.Add Name:="Name_1", Formula:= _
    "let" & Chr(13) & "" & Chr(10) & "    Source = Folder.Files(""C:EXCHANGERLastStage BOX"")
Sheets.Add After:=Sheets(1)
Sheets(2).Name = "INDEX"
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
    "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""Name_1"";Extended Properties=""""" _
    , Destination:=Range("$A$1")).QueryTable
    .CommandType = xlCmdSql
    .CommandText = Array("SELECT * FROM [Name_1]")
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .BackgroundQuery = True
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .PreserveColumnInfo = True
    .ListObject.DisplayName = "Name_1"
    .Refresh BackgroundQuery:=False
End With

Tome make it dynamic, I have come with smth like this so far

Dim i As Integer
i = 1
ActiveWorkbook.Queries.Add Name:=i, Formula:= _
    "let" & Chr(13) & "" & Chr(10) & "    Source = Folder.Files(""C:EXCHANGERLastStage BOX"")

Sheets.Add After:=Sheets(1)
Sheets(2).Name = "INDEX"
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
    "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=i;Extended Properties=""""" _
    , Destination:=Range("$A$1")).QueryTable
    .CommandType = xlCmdSql
    .CommandText = Array("SELECT * FROM [i]")
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .BackgroundQuery = True
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .PreserveColumnInfo = True
    .ListObject.DisplayName = i
    .Refresh BackgroundQuery:=False
End 

and the code rolls fine until it hits

.ListObject.DisplayName = i

which deals only with strings. Any workaround on this one, please?

Leave a Reply

Your email address will not be published. Required fields are marked *