Table of Contents
Removing spaces from a string in VBA refers to the process of eliminating any blank spaces within a string of characters. This can be achieved by using various built-in functions or through custom code. It is a common task in VBA programming, often used for data cleaning and formatting purposes. By removing spaces, the string becomes more concise and easier to manipulate for further processing. This can be useful in a variety of applications, such as creating dynamic reports or performing text analysis.
VBA: Remove Spaces from String
You can use the following basic syntax to remove spaces from a string using VBA:
Sub RemoveSpaces()
Dim i As Integer
For i = 2 To 8
Range("B" & i) = Replace(Range("A" & i), " ", "")
Next i
End Sub
This particular example removes the spaces from each string in the range A2:A8 and outputs the results in the range B2:B8.
The following example shows how to use this syntax in practice.
Example: Using VBA to Remove Spaces from Strings
Suppose we have the following list of strings in Excel:

Suppose we would like to remove the spaces from each string.
We can create the following macro to do so:
Sub RemoveSpaces()
Dim i As Integer
For i = 2 To 8
Range("B" & i) = Replace(Range("A" & i), " ", "")
Next i
End SubWhen we run this macro, we receive the following output:

Column B displays each of the strings in column A with the spaces removed.
Note: You can find the complete documentation for the VBA Replace method .
The following tutorials explain how to perform other common tasks using VBA:
Cite this article
stats writer (2024). How do I remove spaces from a string in VBA?. PSYCHOLOGICAL SCALES. Retrieved from https://scales.arabpsychology.com/stats/how-do-i-remove-spaces-from-a-string-in-vba/
stats writer. "How do I remove spaces from a string in VBA?." PSYCHOLOGICAL SCALES, 24 Jun. 2024, https://scales.arabpsychology.com/stats/how-do-i-remove-spaces-from-a-string-in-vba/.
stats writer. "How do I remove spaces from a string in VBA?." PSYCHOLOGICAL SCALES, 2024. https://scales.arabpsychology.com/stats/how-do-i-remove-spaces-from-a-string-in-vba/.
stats writer (2024) 'How do I remove spaces from a string in VBA?', PSYCHOLOGICAL SCALES. Available at: https://scales.arabpsychology.com/stats/how-do-i-remove-spaces-from-a-string-in-vba/.
[1] stats writer, "How do I remove spaces from a string in VBA?," PSYCHOLOGICAL SCALES, vol. X, no. Y, ص Z-Z, June, 2024.
stats writer. How do I remove spaces from a string in VBA?. PSYCHOLOGICAL SCALES. 2024;vol(issue):pages.
