'Unique name for Query/Pivot table - Macro/VBA/Excel

Backstory
I need to create a macro that can be used by other people that will import data monthly and create 2 pivot tables from two different excel workbooks. The best method I have devised to do this is to have the person download the two files they need into the same folder as this macro-enabled workbook and name them the same for the purpose of querying and pulling the data(i.e. Output1 and Output2) then append with the date and move to a storage folder once they have run the macro and gotten the tables they want(If I am misunderstanding how querying works and the data needs to remain available in the same location and name for the pivot tables to continue existing please let me know) This way I can hardcode the files to pull from and it's minimal effort on their part.

The problem
When I record the macro, it makes a static name for each query with
"ActiveWorkbook.Queries.Add"
Which means that when I go to run it for the second month, I get an error that the query connection already exists and the macro errors out.
I found this code that is supposed to check if the query already exists, and if it does; delete it, but I can't make it work.

Dim qry As WorkbookQuery

If DoesQueryExist(TS) Then
    ' Deleting the query
    Set qry = ThisWorkbook.Queries(TS)
    qry.Delete
End If

I've just placed this inside my macro sub. Can anyone think of why this wouldn't be working? I wasn't able to find very much on the function "DoesQueryExist".
Is there another solution that might work instead that would allow me to just create unlimited queries with arbitrary names instead of having to check and delete?


Thanks


Solution 1:[1]

You need to add the code for DoesQueryExist:

Function DoesQueryExist(ByVal queryName As String) As Boolean
    ' Helper function to check if a query with the given name already exists
    Dim qry As WorkbookQuery
    
    If (ThisWorkbook.Queries.Count = 0) Then
        DoesQueryExist = False
        Exit Function
    End If
    
    For Each qry In ThisWorkbook.Queries
        If (qry.Name = queryName) Then
            DoesQueryExist = True
            Exit Function
        End If
    Next
    DoesQueryExist = False
End Function

Sourced from archive.org.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BigBen