To use a QueryTable in Excel VBA, you create a connection to an external data source (such as a CSV file, a database, or a web page), add a QueryTable object to a worksheet, and then refresh it to pull in the data. The QueryTable object gives you programmatic control over the import: you can set the connection string, define the destination range, adjust refresh options, and handle the data as a table. This guide walks you through the practical steps, from setting up the connection to automating refreshes, and covers the common pitfalls that trip people up.

What You'll Need

  • Microsoft Excel (desktop version for Windows or Mac; QueryTable VBA is not supported in Excel for the web).
  • A data source you can reach: a local file (CSV, TXT), a database you have credentials for, or a web URL that returns tabular data.
  • Basic familiarity with the VBA editor (Alt+F11 on Windows, or the Developer tab > Visual Basic).
  • Macro-enabled workbook (.xlsm) if you plan to save your code.

Step-by-Step

  1. Open the VBA editor and insert a module. Press Alt+F11 (Windows) or go to Developer > Visual Basic (Mac: Developer > Editor). In the Project Explorer, right-click your workbook, choose Insert > Module. This is where you will write the code.
  2. Decide on your data source and connection string. For a CSV file, the connection string looks like "TEXT;" & filePath. For an Access database, it is "OLEDB;Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath. For a web query, use "URL;" & url. The exact syntax depends on the provider; check the documentation for your database driver if unsure.
  3. Write the core macro. Start with a Sub procedure. Declare variables for the worksheet, the QueryTable, and the connection string. For example:
    Sub CreateQueryTable()
        Dim ws As Worksheet
        Dim qt As QueryTable
        Dim connStr As String
        Set ws = ThisWorkbook.Worksheets("Sheet1")
        connStr = "TEXT;" & ThisWorkbook.Path & "\data.csv"
        Set qt = ws.QueryTables.Add(Connection:=connStr, Destination:=ws.Range("A1"))
        With qt
            .TextFileParseType = xlDelimited
            .TextFileCommaDelimiter = True
            .Refresh BackgroundQuery:=False
        End With
    End Sub
    This example imports a comma-delimited CSV into cell A1 and its adjacent cells. Adjust the delimiter and parse type for your file.
  4. Set the destination range correctly. The Destination argument must be a single cell or a range large enough to hold the data. If you specify a single cell, Excel will expand the table automatically. If you specify a fixed range that is too small, you may get a run-time error or truncated data. Use a single cell to avoid this.
  5. Configure refresh options. The Refresh method has parameters: BackgroundQuery (set to False to wait for the refresh to finish), RefreshStyle (xlInsertDeleteCells, xlInsertEntireRows, or xlOverwriteCells), and EnableRefresh. For most scripts, BackgroundQuery:=False is what you want so the next line of code runs only after data arrives.
  6. Handle errors and clean up. Wrap the refresh in error handling to catch connection failures. Also, if you run the macro multiple times, you may create duplicate QueryTables. Check if one already exists at the destination and delete it first, or use a named range and reuse the existing QueryTable object.
  7. Run the macro and verify. Press F5 in the editor or assign the macro to a button. Check that the data appears in the expected location and that column headers are correct. If the data is misaligned, adjust the TextFileColumnDataTypes or the delimiter settings.
  8. Save and secure your workbook. Save as .xlsm. If you plan to share the file, consider whether the connection string contains sensitive paths or credentials; you may want to prompt the user for a file path instead of hard-coding it.

Common Mistakes

  • Using a fixed destination range that is too small. Always use a single cell (e.g., Range("A1")) and let Excel expand the table.
  • Forgetting to set BackgroundQuery to False. If left as True, your code may continue before the data is loaded, leading to empty results.
  • Incorrect connection string syntax. Missing semicolons or wrong provider names cause run-time errors. Test the connection string in a small standalone macro first.
  • Not handling existing QueryTables. Running the macro twice can create overlapping tables. Delete any existing QueryTable at the destination before adding a new one.
  • Ignoring regional settings. Date and number formats in CSV files may be parsed differently depending on your system locale. Use the TextFileColumnDataTypes property to force text or specific formats if needed.

Tips

  • Use Application.ScreenUpdating = False before the refresh and set it back to True afterward to speed up large imports and avoid screen flicker.
  • If you need to import only specific columns, set the TextFileColumnDataTypes array to skip unwanted columns (use xlSkipColumn).
  • For web queries, the URL must point directly to an HTML table or a file; dynamic pages that require JavaScript will not work with QueryTable.
  • Name your QueryTable (e.g., qt.Name = "MyData") so you can refer to it later by name instead of by index.
  • To refresh all QueryTables in a workbook, loop through ThisWorkbook.QueryTables and call Refresh on each.

Troubleshooting

If the macro runs but no data appears, first check that the file path is correct and that the file is not open in another program. For database connections, verify that the provider is installed (e.g., ACE OLEDB provider for Access). If you get a "Data source name not found" error, the driver may be missing or the bitness (32-bit vs 64-bit) may mismatch. Try running the connection string in a small test macro with Debug.Print to see the exact error. If the data loads but columns are misaligned, adjust the delimiter settings or use the Text Import Wizard manually once to see the correct parameters, then replicate them in VBA. If the refresh hangs, set BackgroundQuery:=False and add a timeout using Application.Wait or error handling. Finally, ensure macros are enabled and the workbook is in a trusted location.

Frequently Asked Questions

Can I use QueryTable to import from a web page?

Yes, if the page contains a static HTML table. Use a connection string starting with "URL;" followed by the web address. Pages that load data via JavaScript will not work.

How do I refresh a QueryTable automatically when the workbook opens?

Place a call to the refresh macro in the Workbook_Open event in the ThisWorkbook module, or set the QueryTable's RefreshOnFileOpen property to True.

What is the difference between QueryTable and ListObject?

A ListObject is an Excel table; a QueryTable is the underlying connection that can feed a ListObject. You can have a QueryTable without a ListObject, but a ListObject that is linked to external data uses a QueryTable internally.

Why do I get a "General ODBC Error" when connecting to a database?

This usually means the connection string is wrong, the database file is locked, or the driver is not installed. Double-check the provider name and file path, and ensure the database is not open exclusively.

Can I import only selected columns from a CSV?

Yes. Set the TextFileColumnDataTypes property to an array where each element corresponds to a column; use xlSkipColumn for columns you want to omit.

Does QueryTable work on Excel for Mac?

Yes, but some providers (like certain OLEDB drivers) may not be available. For CSV and text files, the TEXT connection works on Mac. For databases, check that the ODBC driver is installed for macOS.