Excel VBA Pass Array to Sub: Complete Guide and Examples
In this article
To pass an array to a Sub in Excel VBA, you must declare the parameter in the receiving Sub as a Variant or as a specifically typed array (using parentheses), and then call that Sub by passing the array variable as an argument. This process allows you to separate the logic of data collection from the logic of data processing, making your code cleaner, more reusable, and significantly easier to debug.
What You'll Need
- Microsoft Excel installed on a Windows or Mac computer.
- The Developer tab enabled in the Excel Ribbon.
- Basic familiarity with the VBA Editor (ALT + F11).
- A standard module created to house your procedures.
Step-by-Step
- Open the VBA Editor: Press
ALT + F11on your keyboard to open the Visual Basic for Applications editor. If you do not see the Project Explorer on the left, pressCTRL + R. - Insert a Module: Go to the
Insertmenu and selectModule. This ensures your code is stored in a standard module rather than a worksheet or workbook object, which is best practice for general-purpose macros. - Create the Receiving Sub (The Worker): You need a Sub that is designed to accept an array. The most flexible way to do this is by declaring the argument as a
Variant. For example:Sub ProcessData(myArray As Variant) Dim i As Long For i = LBound(myArray) To UBound(myArray) Debug.Print myArray(i) Next i End SubIn this example,myArray As Varianttells VBA that the Sub can accept an array of any data type. UsingLBoundandUBoundis critical because you cannot assume the array starts at index 0 or 1. - Create the Calling Sub (The Controller): Now, create a second Sub that defines the array and sends it to the first Sub.
Sub MainController() Dim dataList() As String ReDim dataList(0 To 2) dataList(0) = "Apple" dataList(1) = "Banana" dataList(2) = "Cherry" ' Pass the array to the worker sub Call ProcessData(dataList) End SubHere,dataListis declared as a dynamic string array, populated with values, and then passed intoProcessData. - Run the Code: Place your cursor inside the
MainControllersub and pressF5. Check the Immediate Window (CTRL + G) to see the array elements printed. - Experiment with Different Array Types: To pass a 2D array (such as a range of cells), you can use the same
Variantapproach. For instance, if you assign a range to a variant variable, VBA automatically creates a 2D array:Sub RangeToArray() Dim myRange As Variant myRange = Range("A1:B10").Value Call ProcessData(myRange) End SubNote that in theProcessDatasub, you would need a nested loop to handle the rows and columns of a 2D array.
Common Mistakes
One of the most frequent errors is attempting to pass an array to a parameter declared as a specific non-array type. For example, if your Sub is defined as Sub ProcessData(myArray As String), VBA expects a single string, not a collection of strings. This will trigger a Type Mismatch error. To fix this, ensure the parameter is either Variant or explicitly declared as an array using parentheses: myArray() As String.
Another common pitfall is forgetting to use LBound and UBound. Many developers hard-code their loops (e.g., For i = 0 To 10). However, if the array is passed from a Range object, it is always 1-based, whereas a standard declared array might be 0-based depending on the Option Base setting. Hard-coding these limits leads to Subscript out of range errors when the array size changes.
Developers also frequently confuse ByVal and ByRef when passing arrays. By default, VBA passes arrays ByRef (By Reference). This means the Sub receives a pointer to the original array. If you modify an element inside the receiving Sub, the original array in the calling Sub is also changed. If you need to protect the original data, you must create a temporary copy of the array inside the Sub.
Tips
For maximum flexibility, always use Variant for the receiving parameter. This allows your Sub to handle both fixed-size arrays, dynamic arrays, and arrays generated from Excel ranges without needing to rewrite the code for every different data type.
When dealing with very large arrays, avoid passing them ByVal (though VBA generally requires ByRef for arrays anyway). Passing by reference is significantly faster because the computer does not have to duplicate the entire dataset in memory; it simply tells the Sub where the existing data is located.
If you are passing a 2D array, use the IsArray() function at the start of your receiving Sub. This acts as a safety check to ensure the passed variable is actually an array before the code attempts to run UBound, which would otherwise cause a crash if a single variable was passed by mistake.
Combine array passing with Option Explicit at the top of your module. This forces you to declare all variables, preventing typos in array names that could lead to the creation of empty, unplanned variants, which are difficult to track during debugging.
Troubleshooting
If you encounter a Type Mismatch (Error 13), check the declaration of your parameter. Ensure the receiving Sub uses As Variant or () As [DataType]. If you are passing a range of cells, remember that Range("A1:B10").Value returns a 2D array, even if only one column is selected. If your Sub is expecting a 1D array, this will cause a mismatch.
If you see Subscript out of range (Error 9), it usually means your loop is trying to access an index that doesn't exist. Use the Debug.Print LBound(myArray) and Debug.Print UBound(myArray) commands immediately before the loop to verify the actual boundaries of the array being passed.
If the values in your original array are changing unexpectedly after the Sub runs, remember that arrays are passed ByRef. To prevent this, you can use the WorksheetFunction.Index method or a manual loop to copy the passed array into a local array variable within the Sub, ensuring the original remains untouched.
If the code runs but the Immediate Window is empty, ensure you have actually populated the array in the calling Sub before the Call statement. A declared but uninitialized dynamic array has no bounds, and calling UBound on it will result in an error.
Frequently Asked Questions
Can I pass a fixed-size array to a Sub?
Yes, but the receiving Sub must declare the parameter as a Variant or as a dynamic array (using parentheses). You cannot specify the exact size (e.g., myArray(1 to 10) As String) in the Sub's parameter list.
What is the difference between passing a Range and passing an Array?
Passing a Range object passes a reference to the Excel cells, allowing you to change cell colors or formulas. Passing an array (via .Value) passes only the data values into memory, which is significantly faster for calculations.
How do I pass a 2D array to a Sub?
Declare the parameter as Variant. Inside the Sub, use two nested For...Next loops: the outer loop for the first dimension (rows) and the inner loop for the second dimension (columns).
Can a Sub return an array back to the main procedure?
A Sub cannot return a value. To return an array, you must use a Function. Declare the Function's return type as Variant or a specific array type, and assign the array to the Function name at the end of the routine.
Does passing an array slow down my macro?
No, because VBA passes arrays ByRef. Instead of copying the data, it passes the memory address. This is the most efficient way to handle large datasets in VBA.
Why do I get an error when passing a single cell as an array?
A single cell is not an array; it is a single value. If your Sub expects an array, you must either wrap the single cell in an array or use the IsArray() check to handle single values differently.