Smart Systems for Home

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

Excel VBA Debug Print Array: How to View Array Contents

· 7 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

To debug print an array in Excel VBA, you must use a loop (such as For...Next) to iterate through each element and send them to the Immediate Window using the Debug.Print command, as VBA does not support printing an entire array with a single command. This process allows developers to inspect the internal state of a variable array or a multi-dimensional array during runtime to ensure data is being processed correctly before it is written to a worksheet.

What You'll Need

  • Microsoft Excel installed on a Windows PC.
  • The Visual Basic Editor (VBE) open (accessible via ALT + F11).
  • The Immediate Window enabled (accessible via CTRL + G if not visible).
  • A declared array variable containing data to be inspected.

Step-by-Step

  1. Open the Visual Basic Editor: Press ALT + F11 from your Excel workbook to open the VBE. Ensure your code is written within a Standard Module or a Sheet/Workbook module.
  2. Enable the Immediate Window: If you do not see a white pane at the bottom of your screen, go to the top menu and select View > Immediate Window or press CTRL + G. This is where the Debug.Print output will appear.
  3. Declare and Populate Your Array: Ensure your array has data. For example, if you are testing a simple one-dimensional array, you might use Dim myArr As Variant: myArr = Array("Apple", "Banana", "Cherry").
  4. Set a Breakpoint: To stop the code at the exact moment you want to inspect the array, click in the left-hand margin next to the line of code where the array is fully populated. A brown circle will appear, indicating a breakpoint.
  5. Implement a For...Next Loop for 1D Arrays: Since Debug.Print myArr will only output the type of the variable (or throw an error), you must write a loop. Use the LBound and UBound functions to ensure the loop covers the entire range of the array regardless of its starting index.

    Example code for a 1D array:
    Dim i As Long
    For i = LBound(myArr) To UBound(myArr)
        Debug.Print "Index " & i & ": " & myArr(i)
    Next i
  6. Implement Nested Loops for 2D Arrays: If you are dealing with a 2D array (common when reading a range of cells into a variant), you need two loops: one for rows and one for columns.

    Example code for a 2D array:
    Dim r As Long, c As Long
    For r = LBound(myArr, 1) To UBound(myArr, 1)
        For c = LBound(myArr, 2) To UBound(myArr, 2)
            Debug.Print "Row " & r & ", Col " & c & ": " & myArr(r, c)
        Next c
    Next r
  7. Run the Macro: Press F5 to run the code. When the execution hits your breakpoint, the code will pause.
  8. Execute the Debug Code: You can either let the code run through the loop naturally or, if you have written the loop as a separate helper subroutine, call it from the Immediate Window by typing the name of the sub followed by a colon (e.g., PrintArray myArr:) and pressing Enter.
  9. Inspect the Results: Look at the Immediate Window. You will see a vertical list of every element in your array, its index, and its current value.

Common Mistakes

One of the most frequent errors is attempting to use Debug.Print myArr directly. In many modern programming languages, printing an array object provides a formatted list of its contents. In VBA, this results in a Type Mismatch error because Debug.Print expects a string or a basic numeric value, not a complex array object.

Another common mistake is hard-coding the loop limits (e.g., For i = 0 To 10). If the array size changes or if the array is 1-based instead of 0-based (which often happens when pulling data from an Excel Range), the code will either miss elements or crash with a Subscript out of range error. Always use LBound() and UBound() to dynamically determine the array boundaries.

Users also frequently forget to clear the Immediate Window. Over time, the window fills with thousands of lines of previous debug sessions, making it difficult to tell which output belongs to the current run. Right-click inside the Immediate Window and select Clear All before starting a new debug session.

When working with 2D arrays, a common mistake is swapping the dimension indices in UBound. Remember that UBound(myArr, 1) refers to the first dimension (usually rows) and UBound(myArr, 2) refers to the second dimension (usually columns). Swapping these will cause the loop to attempt to access indices that do not exist.

Tips

For arrays with a massive amount of data, printing every single element to the Immediate Window can significantly slow down your macro and may even cause the VBE to hang. In these cases, implement a conditional print or a limit, such as If i < 100 Then Debug.Print myArr(i), to only see the first few entries.

To make the output more readable, use a delimiter like a tab character vbTab or a pipe " | " when printing 2D arrays. This helps visually separate columns in the Immediate Window, simulating a table structure. For example: Debug.Print myArr(r, c) & vbTab followed by a Debug.Print "" (empty string) after the inner loop finishes to create a new line for each row.

Consider creating a dedicated "PrintArray" helper procedure in a separate module. Instead of writing a loop every time you need to check an array, you can simply call Call PrintArray(myArr). To make this work, the helper sub must accept a Variant as an argument, allowing it to handle arrays of different sizes and types.

If you prefer a visual interface over text, use the Locals Window (View > Locals Window). While Debug.Print is better for logging a sequence of changes, the Locals Window allows you to expand an array variable and see all its indices and values in a tree view without writing any extra code. This is often faster for a quick snapshot of the data.

Troubleshooting

If you receive a Subscript out of range error during your debug loop, the first thing to check is the array's initialization. Ensure the array has actually been dimensioned or assigned values before the loop runs. If the array is dynamic and has not been ReDimed, UBound will throw an error. You can wrap your debug loop in an On Error Resume Next block or check if the array is initialized using a custom function to avoid this crash.

If the Immediate Window is not displaying any output despite the code running, check if you have any filters or if the window is simply scrolled to the top. Ensure that you are using Debug.Print and not MsgBox; while MsgBox works for single values, using it in a loop with an array of 1,000 items will force you to click "OK" 1,000 times, effectively freezing your application.

If you see Empty or Null values in your output, this indicates that the array was dimensioned but the specific indices were never assigned a value. This is a critical debugging discovery, as it tells you that your data-loading logic is skipping certain elements.

If the output looks jumbled or values are running together, ensure you are not using Debug.Print inside a loop without proper string concatenation or line breaks. Each Debug.Print call automatically adds a new line unless you are specifically manipulating the output string. If you are building a long string to print once at the end, ensure you include vbCrLf to maintain readability.

Frequently Asked Questions

Can I print an array to the Excel sheet instead of the Immediate Window?

Yes. If the array is a 2D array, you can write the entire array to a range in one step using Range("A1").Resize(UBound(myArr, 1), UBound(myArr, 2)).Value = myArr. For 1D arrays, you must loop through the elements and assign them to individual cells.

Why does Debug.Print show my array as a single value or error?

VBA cannot resolve an entire array into a single string. You must iterate through the indices using a loop to print each element individually.

How do I handle arrays that might be empty?

You can check if an array is allocated by attempting to call UBound within an error-handling block. If UBound fails, the array is uninitialized and cannot be printed.

Is there a way to print only specific elements of a large array?

Yes, you can add an If statement inside your For loop to only Debug.Print elements that meet certain criteria, such as If myArr(i) = "Error" Then Debug.Print i.

Does this work for arrays of objects or custom classes?

It works, but Debug.Print myArr(i) will only print the default property of the object. To see specific properties of an object within an array, you must specify the property, such as Debug.Print myArr(i).Name.