Search code examples
excelvbafor-loopdynamicpowerquery

Trouble using VBA variables to define Power Query source


PDF Path is the file path to the PDF, removed for confidentiality - code works with this in place.

I am having trouble inserting a variable into the last line of this VBA code. Essentially, I need to grab specific tables from varying PDFs. There are 2 tables to each page of these PDFs and I always need the 2nd one, never the 1st. The user inputs how many pages to the PDF there are and this loop will run and query the necessary tables.

Wherever it says Table002, I need it to be the variable Table_No, so that when it goes back through the loop, it grabs Table004 then Table 006 and so on, but I keep running into different errors. This code works as expected for the first loop, my trouble is getting it to grab the new table rather than the one that it has already grabbed. Can anyone help? Does my variable need to be a different data type?

Dim Table_Max As Integer
Dim Ack_Pages As Integer
Dim Table_No As String

Ack_Pages = InputBox("Enter the number of pages on the acknowledgement file.")
Table_Max = Ack_Pages * 2

For i = 2 To Table_Max Step 2
    Table_No = "Table00" & i
        ActiveWorkbook.Queries.Add Name:=Table_No, Formula:= _
            "let" & Chr(13) & "" & Chr(10) & "    Source = Pdf.Tables(File.Contents(""" & PDFPath & """), [Implementation=""1.3""])," & Chr(13) & "" & Chr(10) & "    Table002 = Source{[Id=""Table002""]}[Data]," & Chr(13) & "" & Chr(10) & "    #""Changed Type"" = Table.TransformColumnTypes(Table002,{{""Column1"", type text}, {""Column2"", type text}, {""Column3"", type text}, {""Column4"", type text}, {""Column5"", type text}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & "    #""Changed Type"""

Solution

    • Id="Tablexxx" should be changed as below
    ActiveWorkbook.Queries.Add Name:=Table_No, Formula:= _
            "let" & Chr(13) & "" & Chr(10) & "    Source = Pdf.Tables(File.Contents(""" & PDFPath & """), [Implementation=""1.3""])," & Chr(13) & "" & Chr(10) & "    Table002 = Source{[Id=""" & Table_No & """]}[Data]," & Chr(13) & "" & Chr(10) & "    #""Changed Type"" = Table.TransformColumnTypes(Table002,{{""Column1"", type text}, {""Column2"", type text}, {""Column3"", type text}, {""Column4"", type text}, {""Column5"", type text}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & "    #""Changed Type"""