DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk5 min

Create Power Query Connections for Every Excel Table with VBA

A VBA pattern for creating a Power Query query and workbook connection for every Excel table, with guidance on reruns, naming collisions, headers, and limitations.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To create a Power Query query for each Excel table, loop through the workbook’s worksheets and their ListObjects, add an M query that reads the table through Excel.CurrentWorkbook(), then create a Mashup OLE DB connection whose location matches the query name. The pattern below is designed for Excel desktop versions with the Get & Transform object model; it avoids duplicate-name errors on repeat runs by updating existing queries and connections.

How the macro maps tables to Power Query

An Excel table is a ListObject. Power Query can access it by name with Excel.CurrentWorkbook(){[Name="TableName"]}[Content]. Microsoft says Excel.CurrentWorkbook() returns tables, named ranges, and dynamic arrays—not worksheets (Microsoft: Excel.CurrentWorkbook).

As an Amazon Associate I earn from qualifying purchases.

The VBA object model keeps queries and connections in separate collections. Workbook.Queries contains the workbook’s Get & Transform queries, while Workbook.Connections contains workbook connections such as OLE DB connections (Microsoft: Workbook.Queries; Microsoft: Workbook.Connections). The query name and the connection’s Location must match.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

VBA macro: create or update a query and connection for each table

Paste this code into a standard VBA module in the workbook that contains the source tables. It creates one query and a corresponding Mashup connection per table. If a query or connection with the target name already exists, it updates the query or deletes and recreates the connection rather than failing on a duplicate name.

Option Explicit

Public Sub CreatePowerQueryConnectionsForAllTables()
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim lo As ListObject
    Dim tableName As String
    Dim queryName As String
    Dim mFormula As String
    Dim connectionName As String
    Dim conn As WorkbookConnection

    Set wb = ThisWorkbook

    For Each ws In wb.Worksheets
        For Each lo In ws.ListObjects
            tableName = lo.Name
            queryName = MakeQueryName(tableName)
            connectionName = "Query - " & queryName
            mFormula = BuildTableQuery(tableName)

            If QueryExists(wb, queryName) Then
                wb.Queries(queryName).Formula = mFormula
            Else
                wb.Queries.Add Name:=queryName, Formula:=mFormula
            End If

            ' Recreate the connection so its Location matches the query name.
            If ConnectionExists(wb, connectionName) Then
                wb.Connections(connectionName).Delete
            End If

            Set conn = wb.Connections.Add2( _
                Name:=connectionName, _
                Description:="Power Query connection for table " & tableName, _
                ConnectionString:="OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=" & queryName & ";Extended Properties=""""", _
                CommandText:="SELECT * FROM [" & queryName & "]", _
                lCmdtype:=xlCmdSql, _
                CreateModelConnection:=False, _
                ImportRelationships:=False)
        Next lo
    Next ws
End Sub

Private Function BuildTableQuery(ByVal tableName As String) As String
    BuildTableQuery = "let" & vbCrLf & _
        "    Source = Excel.CurrentWorkbook(){[Name=""" & EscapeMText(tableName) & """]}[Content]" & vbCrLf & _
        "in" & vbCrLf & _
        "    Source"
End Function

Private Function EscapeMText(ByVal value As String) As String
    EscapeMText = Replace(value, """", """"")
End Function

Private Function MakeQueryName(ByVal tableName As String) As String
    ' Table names normally meet query-name needs. Replace unsupported punctuation
    ' and keep the original table name in the M source expression.
    Dim result As String
    Dim i As Long
    Dim ch As String

    result = ""
    For i = 1 To Len(tableName)
        ch = Mid$(tableName, i, 1)
        If ch Like "[A-Za-z0-9_]" Then
            result = result & ch
        Else
            result = result & "_"
        End If
    Next i
    If Len(result) = 0 Then result = "TableQuery"
    MakeQueryName = result
End Function

Private Function QueryExists(ByVal wb As Workbook, ByVal queryName As String) As Boolean
    Dim q As WorkbookQuery
    On Error Resume Next
    Set q = wb.Queries(queryName)
    QueryExists = Not q Is Nothing
    On Error GoTo 0
End Function

Private Function ConnectionExists(ByVal wb As Workbook, ByVal connectionName As String) As Boolean
    Dim c As WorkbookConnection
    On Error Resume Next
    Set c = wb.Connections(connectionName)
    ConnectionExists = Not c Is Nothing
    On Error GoTo 0
End Function

The connection string follows Microsoft’s documented Mashup connection shape: provider Microsoft.Mashup.OleDb.1, Data Source=$Workbook$, and Location set to the query name. The accompanying command selects from that same name (Microsoft Open Specifications: Retrieving Data From an SQL Source using Get & Transform). The object-model documentation and format example establish the relevant pieces, but do not promise identical behavior for every Excel build; verify this pattern in the desktop version and workbook format you use.

Important naming assumption

The helper converts punctuation in a table name to underscores to form a query name. If two distinct table names convert to the same query name—for example, names that differ only by punctuation—the macro can target the same query twice. Ensure table names produce unique query names, or change MakeQueryName to add a stable suffix. The M source continues to use the actual Excel table name.

What this macro does not configure

It creates a query and a workbook connection; it does not set up a worksheet output table or specify a load-to-worksheet destination. Do not assume the result is loaded onto a sheet just because the connection exists. Configure the desired load destination separately in Excel if you need visible output.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Run the macro safely

  1. Save a copy of the workbook as a macro-enabled Excel workbook if it is not already one.
  2. Confirm each source range is an Excel table and note its table name. In Excel, select a cell in the table and look for the table name on the Table Design tab.
  3. Open the VBA editor, insert a standard module, paste the code, and run CreatePowerQueryConnectionsForAllTables.
  4. In Excel, open Data > Queries & Connections and check that each table has a query. Confirm that each corresponding connection appears in the workbook’s connections list.
  5. Run the macro a second time and check that it completes without duplicate-name errors and that the existing queries still point to the intended tables.

Reruns, blank tables, and headers

Repeated runs

The macro updates an existing query’s formula and recreates the matching connection. It does not remove queries or connections for tables that have since been deleted or renamed, so those old entries may remain in the workbook and require manual cleanup. If other workbook features depend on a connection, deleting and recreating it may also affect those dependencies; review them before using this rerun behavior in a production workbook.

Blank tables and tables with headers

Test a blank table as well as populated tables before relying on downstream steps. The example’s M formula simply returns the table’s content; it does not add type conversions or repair missing or duplicate headers. Use meaningful, unique column names before building transformations that refer to those names.

If your macro also creates tables from ranges, specify whether the source range has headers instead of relying on Excel’s guess. A Microsoft Q&A answer about a reported case of headings becoming Column1, Column2, and so on recommends passing xlYes to the table-creation method when the range has headings. That is community troubleshooting guidance, not a guarantee about every Excel version (Microsoft Q&A: reported header-renaming issue).

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Version and workbook-format considerations

Microsoft documents the Get & Transform query collection for Excel 2016 onward. Because the cited VBA references describe the collections but do not define a complete compatibility matrix for every desktop build, test the macro in the Excel installation where it will run.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Power Query connector limitations also depend on the host and file format. Microsoft’s Excel connector guidance notes that Power Query in Excel and Power Query Online cannot access encrypted Excel files; Power Query Online does not support password-protected Excel files; and legacy .xls or .xlsb files may require the Access Database Engine provider. These connector notes are not, by themselves, a complete statement of whether a particular VBA-generated desktop connection will work (Microsoft: Power Query Excel connector).

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

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

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.