Excel VBA Trim Array: How to Remove Extra Spaces
In this article
To trim an array in Excel VBA, you must iterate through each element of the array using a loop (such as a For...Next loop) and apply the Trim() function to each individual item. Because VBA does not provide a native "TrimArray" function that can process an entire collection of strings at once, you must target each index one by one to strip leading and trailing spaces from the text.
What You'll Need
- Microsoft Excel installed on Windows.
- Access to the Visual Basic for Applications (VBA) editor (Alt + F11).
- A dataset containing strings with inconsistent spacing (leading, trailing, or both).
- Basic familiarity with declaring variables and arrays in VBA.
Step-by-Step
- Open the VBA Editor: Launch Excel and press
Alt + F11on your keyboard. This opens the VBA IDE. Go toInsert > Moduleto create a new space for your code. - Declare Your Variables: You need to define the array that holds your data and a counter variable for the loop. Use the
Varianttype if your array contains mixed data, orStringif it is strictly text. For example:Dim myData() As StringandDim i As Long. - Populate the Array: Load your data into the array. You can do this manually or by pulling a range from a worksheet. A common method is assigning a range directly to a variant array:
myData = Range("A1:A10").Value. Note that when pulling from a range, VBA creates a 2D array, even if only one column is selected. - Set Up the Loop: Use a
For...Nextloop to traverse the array from the lower bound to the upper bound. This ensures every single element is processed regardless of the array size. UseLBound(myData)andUBound(myData)to make your code dynamic so it works regardless of how many items are in the list. - Apply the Trim Function: Inside the loop, assign the trimmed value back to the original array index. The syntax is
myData(i) = Trim(myData(i)). TheTrimfunction specifically removes spaces from the beginning and the end of a string; it does not remove double spaces between words. - Handle 2D Arrays (If Applicable): If you loaded your array from a worksheet range, you must use a nested loop or specify the second dimension. For a single column range, the code would be
myData(i, 1) = Trim(myData(i, 1)). - Output the Results: Once the loop finishes, write the cleaned array back to the worksheet or use it in your further calculations. For example:
Range("B1:B10").Value = myData.
Common Mistakes
One of the most frequent errors is attempting to use Trim(myArray). In VBA, the Trim function expects a single string as an argument. Passing an entire array into the function will result in a Type Mismatch error. You must always loop through the elements.
Another common mistake is ignoring the dimensions of the array. When you assign a range of cells to a variant variable (e.g., arr = Range("A1:A10").Value), VBA creates a 2-dimensional array where the first dimension is the row and the second is the column. If you try to access it as a 1D array (e.g., arr(i)), you will receive a Subscript out of range error. You must use arr(i, 1).
Developers also often confuse the VBA Trim() function with the Excel Worksheet function TRIM(). The VBA version only removes leading and trailing spaces. The Worksheet version removes leading and trailing spaces AND replaces internal multiple spaces with a single space. If you need the Worksheet behavior, you must call it via Application.WorksheetFunction.Trim().
Tips
For maximum performance when dealing with very large arrays (thousands of rows), avoid writing to the sheet inside the loop. Instead, perform all the trimming operations within the array in memory and write the entire array back to the sheet in one single operation. This reduces the number of interactions between VBA and the Excel interface, which is the primary cause of slow macros.
If you are unsure if your array contains nulls or non-string values, wrap your trim logic in a check. Use If VarType(myData(i)) = vbString Then to ensure you are only attempting to trim actual text, which prevents errors when encountering numeric values or empty cells.
Consider creating a reusable function. Instead of writing the loop every time, create a Function TrimArray(inputArray As Variant) As Variant. This allows you to pass any array into the function and receive a cleaned version back, keeping your main subroutines clean and readable.
Troubleshooting
If you encounter a "Type Mismatch" error, check if your array contains Null values or Error values (like #N/A). The Trim function cannot process these. To fix this, use the CStr() function to convert the element to a string first: myData(i) = Trim(CStr(myData(i))).
If you get a "Subscript out of range" error, it usually means your loop is trying to access an index that doesn't exist. Double-check that you are using LBound and UBound rather than hard-coding numbers like 1 to 10. If you are using a 2D array from a range, ensure you have specified both dimensions, such as (i, 1).
If the spaces are still there after running the code, you might be dealing with non-breaking spaces (ASCII character 160), which are common in data imported from the web. The standard Trim function does not recognize these as spaces. To solve this, use the Replace function before trimming: myData(i) = Trim(Replace(myData(i), Chr(160), " ")).
Frequently Asked Questions
Does Trim() remove spaces between words?
No, the VBA Trim() function only removes spaces from the start and the end of a string. To remove extra spaces between words, you must use Application.WorksheetFunction.Trim().
Can I trim a dynamic array?
Yes. By using LBound and UBound in your loop, your code will automatically adjust to the size of the dynamic array regardless of how many elements it contains.
Is there a way to trim an array without a loop?
No, there is no single-command method in VBA to trim an entire array. You must iterate through the elements using a loop or use a custom-built function that handles the looping for you.
What is the difference between LTrim and RTrim?
LTrim only removes spaces from the left (leading) side of the string, while RTrim only removes spaces from the right (trailing) side. Trim performs both actions simultaneously.
Will trimming an array affect the original data on the sheet?
Not automatically. Trimming the array only changes the data stored in the computer's memory. To update the worksheet, you must explicitly write the modified array back to the cells.
How do I handle arrays with multiple columns?
You will need a nested loop. The outer loop iterates through the rows (first dimension), and the inner loop iterates through the columns (second dimension), applying the Trim function to myData(row, col).