Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Excel VBA For Each Row In Table

· 9 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

You can loop through every row in an Excel table using a For Each...Next statement with a ListObject variable, which is cleaner and safer than looping through a range by row number. First, insert a table from your data (Insert > Table), then open the VBA Editor (Alt+F11), insert a standard module, and paste a block of code that defines the table, iterates through each row, and performs an action on the data. This approach automatically handles new rows added to the table later, adhering to the table's structure rather than a fixed range.

What You'll Need

  • A computer running Microsoft Excel (2010 or later is recommended for full table support).
  • A set of data that you want to treat as a structured table (e.g., a list of sales, inventory items, or employee records).
  • The Visual Basic for Applications (VBA) editor, which is included with most Office installations.
  • Basic familiarity with the VBA Editor interface, including how to insert a module and run a macro.

Step-by-Step

  1. Prepare your data and create a table. Highlight your data range (including headers). Go to the Insert tab on the Ribbon and click the Table button. In the dialog, ensure "My table has headers" is checked and click OK. Excel will give the table a generic name like "Table1" or "Table2"; this name is visible in the Name Box (top-left of the sheet) and in the VBA Editor under "Project - VBAProject (Workbook1)" under the sheet object.
  2. Open the VBA Editor. In Excel, press Alt + F11 on your keyboard. This will launch the separate window dedicated to writing and running macros. You will typically see a window labeled "Project - VBAProject (Book1)" on the left.
  3. Insert a standard module. In the VBA Editor, right-click on the name of your workbook in the project explorer (usually "VBAProject (Book1)"). From the context menu, hover over Insert and select Module. A new, empty window will appear on the right side.
  4. Define the table variable. In the module window, start by declaring a variable that points to the table object. The most reliable way is to name the table directly in the code, which requires the table name to be known. You can find the table name in the Name Box (top-left corner of the Excel window) when the table is selected, or in the VBA Editor under the sheet name in the project explorer. The line of code to declare the variable and set it to the table looks like this:
    Dim tbl As ListObject
    Set tbl = ThisWorkbook.Worksheets("Sheet1").ListObjects("Table1")
    Replace "Sheet1" with the actual name of your worksheet and "Table1" with the actual name of your table. It is good practice to wrap this in a With block if you are performing multiple actions on the table.
  5. Write the For Each loop. The core logic uses the For Each statement to iterate over every ListRow in the table. The structure is: For Each row In tbl.ListRows. Inside the loop, you will write the code to process that specific row. After the loop, you need a Next row statement to move to the next row.
  6. Perform an action on the current row. Inside the loop, you can access the data in the current row using the row.Range property. This returns a Range object representing the entire row of the table. You can then read values from cells using standard Range syntax, such as row.Range.Cells(1).Value for the first cell in that row, or row.Range(1) for the first cell. You can also write values back to the table using row.Range.Cells(1).Value = "New Value".
  7. Complete the loop and run the macro. Your code should look something like this:
    Sub LoopThroughTable()
        Dim tbl As ListObject
        Dim rw As ListRow
        
        ' Set the variable to point to the table
        Set tbl = ThisWorkbook.Worksheets("Sheet1").ListObjects("Table1")
        
        ' Loop through each row in the table
        For Each rw In tbl.ListRows
            ' Example: Print the value of the first cell in the row to the Immediate Window
            Debug.Print rw.Range.Cells(1).Value
            
            ' Example: Set the value of the second cell to "Processed"
            ' rw.Range.Cells(2).Value = "Processed"
        Next rw
    End Sub
    To run this code, go back to your Excel window (Alt+F11 to toggle between windows or just click on the Excel sheet). Press Alt + F8, select the macro name LoopThroughTable, and click Run. The code will execute, and if you have a line with Debug.Print, you can see the output by pressing Ctrl + G in the VBA Editor to open the Immediate Window.
  8. Understand dynamic behavior. The power of using ListObject and ListRows is that the loop automatically adjusts. If you add or delete rows in the Excel table after the macro runs, the next time you run the macro, it will process the new rows as well. This is because the loop is based on the table's current structure, not a fixed range of cells like A1:A10.

Common Mistakes

  • Using a fixed range instead of a table variable. A common error is to loop through a range like For i = 1 to 10 or For Each cell in Range("A1:A10"). If you later add a new row at the top of your data, this fixed range will miss it. Using a ListObject ensures the loop always covers the entire dynamic table.
  • Confusing the sheet name and the table name. When setting the table variable, you must reference both the sheet and the table. It is easy to accidentally use the sheet name where the table name should be, or vice versa, which will cause a runtime error (Subscript out of range).
  • Modifying the table structure inside the loop. While you can read and write values to cells, it is generally not safe to add or delete rows (tbl.ListRows.Add or tbl.ListRows.Delete) while you are in the middle of iterating over them with a For Each loop. This can cause unexpected behavior or errors. It is safer to complete a pass through the data, then perform structural changes.
  • Not handling errors. If the table name is misspelled or the sheet name is incorrect, the line Set tbl = ... will stop execution with a runtime error. A robust script would include error handling (e.g., On Error GoTo ErrorHandler) to inform the user that something went wrong rather than the VBA Editor popping up with a cryptic error message.

Tips

  • Use the Immediate Window for debugging. The Debug.Print statement is invaluable. It writes output directly to the Immediate Window in the VBA Editor. This allows you to see the data being processed one row at a time without creating a new report in your Excel sheet.
  • Work with specific columns using Index. Instead of referencing cells by their position (e.g., Cells(1)), it is often more readable to reference them by their table column index. You can get a range for a specific column using tbl.ListColumns("ColumnName").Range. If you need to access a cell within that column for a specific row, you can use tbl.ListColumns("ColumnName").DataBodyRange.Cells(rw.Index, 1).Value, where rw.Index is the number of the row being processed.
  • Consider using a With block. If you need to perform multiple actions on the same table, wrapping the code in a With tbl ... End With block can make the code cleaner and less prone to typos. For example:
    With tbl
        For Each rw In .ListRows
            ' Action using tbl.ListRows(...) or .ListColumns(...)
        Next rw
    End With
  • Optimize for performance on large tables. For very large tables (thousands of rows), looping through each row in VBA can be slow. If you only need to read data, try to use Excel formulas or Power Query (Get & Transform) for the heavy lifting, as they are significantly faster. Use VBA loops for data transformation, formatting, or sending data to other systems.

Troubleshooting

If the macro does not run or produces an error, check the following in order:

  • Check the table name in Excel. The most common cause of a runtime error is using a table name in the VBA code that does not match the actual name in Excel. Go to the Name Box (top-left of the Excel window) and click the table name. Verify the exact name shown there, including any spaces or special characters, and update your VBA code to match it perfectly.
  • Verify the worksheet name. Ensure that the sheet name you are referencing in the VBA code matches the tab name in Excel exactly. Sheet names can be changed, and they cannot contain spaces. If your tab is named "Sales Data", your code must use "SalesData" or "[Sales Data]Sheet1" depending on how the workbook is saved.
  • Run in the correct context. If your table is on a different worksheet than the one where you are running the macro, you must include the worksheet name in your reference. For example, ThisWorkbook.Worksheets("Sheet1"). If you just write ActiveWorkbook.Worksheets("Sheet1") while a different sheet is selected, it will fail.
  • Check for overlapping ranges. Ensure that the table you are looping through does not overlap with another table or a named range that might be modified by your code. Overlapping ranges can cause unpredictable behavior and errors.
  • Ensure the table has headers. The ListRows collection represents the data body of the table, which starts below the headers. If you are trying to access the headers using tbl.ListRows, you will get an error or empty results. To access header data, use tbl.HeaderRowRange.

Frequently Asked Questions

Can I loop through only the visible rows in a filtered table?

Yes, but you must check the .Hidden property of each row. The code would look like: For Each rw In tbl.ListRows: If Not rw.Hidden Then ' Process row' End If: Next rw. This ensures that only the currently visible rows are processed.

What is the difference between a ListObject and a Range?

A ListObject is a specific object in Excel that represents a table, with properties like HeaderRowRange, DataBodyRange, and ListColumns. A standard Range is just a selection of cells, which can be part of a table or not. Using a ListObject is recommended for tables because it provides structure and makes the code more readable and maintainable.

How do I access a cell in a specific column by name?

You can use the ListColumns property. For example, to get the value in the "Name" column for the current row rw, you would write rw.ListColumns("Name").Range.Value. This is more robust than using cell numbers, as it will continue to work even if you insert or delete columns before the "Name" column.

Will my loop break if I delete a row while it is running?

Yes, looping through a collection while modifying that collection (by deleting items) is a common cause of runtime errors. It is best to finish one complete pass through the data before performing any structural changes like adding or deleting rows.

Can I use this code in Excel Online or Excel for Mac?

Yes, the VBA Editor and the ListObject object are available in Excel for Mac and Excel Online, but with some limitations. The interface and menu paths can differ slightly. Also, some advanced VBA features may not be supported in the web version. However, the basic syntax for looping through a table is the same.