Удаление лишних пробелов из строк с помощью кода VBA Excel. Функции LTrim, RTrim, Trim. Встроенная функция рабочего листа и пользовательская функция. Пример.
- LTrim(строка) — удаление пробелов слева;
- RTrim(строка) — удаление пробелов справа;
- Trim(строка) — удаление пробелов слева и справа.
Встроенная функция рабочего листа
Функция VBA Trim удаляет пробелы только по краям строки, не затрагивая двойные, тройные и т.д. пробелы внутри текста. Для удаления всех лишних пробелов следует использовать встроенную функцию Trim рабочего листа Excel.
Синтаксис функции Trim рабочего листа:
WorksheetFunction.Trim(строка) |
Пользовательская функция
Можно бороться с лишними пробелами и с помощью пользовательской функции:
Function myTrim(text As String) As String ‘Удаляем пробелы слева и справа строки text = Trim(text) ‘Удаляем лишние пробелы внутри строки Do While InStr(text, » «) text = Replace(text, » «, » «) Loop myTrim = text End Function |
Пример удаления лишних пробелов
Сократим лишние пробелы в одной и той же строке с помощью функции Trim VBA, встроенной функции Trim рабочего листа Excel, пользовательской функции myTrim и сравним результаты.
Sub Primer() Dim a1 As String a1 = » Жили у бабуси « MsgBox Trim(a1) & vbCrLf _ & WorksheetFunction.Trim(a1) _ & vbCrLf & myTrim(a1) End Sub |
Чтобы код примера сработал без ошибок, код пользовательской функции myTrim должен быть добавлен в тот же модуль.
In this Article
- Trim Function
- Trim Spaces Before and After Text
- Trim Multiple Spaces Before and After Text
- VBA Trim will NOT Remove Multiple Spaces Between Words
- Trim as a Worksheet Function
- Use Worksheet Trim Function in VBA
- Difference Between WorksheetFunction.Trim and VBA Trim
- Use VBA to add Trim Function in a Range
- LTrim Function
- RTrim Function
- Remove all spaces from text
This tutorial will demonstrate how to use the Trim, LTrim, and RTrim VBA functions as well as the Trim worksheet function.
Trim Function
The VBA Trim function removes (“trims”) erroneous spaces before and after strings of text.
Trim Spaces Before and After Text
The VBA Trim function will remove spaces before and after strings of text:
Sub TrimExample_1()
MsgBox Trim(" I love excel ")
'Result is: "I love excel"
MsgBox Trim(" I love excel")
'Result is: "I love excel"
MsgBox Trim("I love excel ")
'Result is: "I love excel"
End Sub
Trim Multiple Spaces Before and After Text
This includes trimming multiple spaces before and after text:
Sub TrimExample_2()
MsgBox Trim(" I love excel ")
'Result is: "I love excel"
MsgBox Trim(" I love excel")
'Result is: "I love excel"
MsgBox Trim("I love excel ")
'Result is: "I love excel"
End Sub
VBA Trim will NOT Remove Multiple Spaces Between Words
However, the Trim function will not remove multiple spaces in between words:
Sub TrimExample_3()
MsgBox Trim(" I love excel ")
'Result is: "I love excel"
MsgBox Trim(" I love excel")
'Result is: "I love excel"
MsgBox Trim("I love excel ")
'Result is: "I love excel"
End Sub
Trim as a Worksheet Function
However, the Excel Trim worksheet function can be used to remove extra spaces between words:
Use Worksheet Trim Function in VBA
To use the Excel Trim Function in VBA, call it by using WorksheetFunction:
Sub TrimExample_4()
Msgbox WorksheetFunction.Trim(" I love excel ")
'Result is: "I love excel"
Msgbox WorksheetFunction.Trim(" I love excel")
'Result is: "I love excel"
Msgbox WorksheetFunction.Trim("I love excel ")
'Result is: "I love excel"
End Sub
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Difference Between WorksheetFunction.Trim and VBA Trim
This will demonstrate the differences between Trim and WorksheetFunction.Trim:
Sub TrimExample_5()
Msgbox WorksheetFunction.Trim(" I love excel ")
'Result is: "I love excel"
Msgbox Trim(" I love excel ")
'Result is: "I love excel"
Msgbox WorksheetFunction.Trim(" I love excel")
'Result is: "I love excel"
Msgbox Trim(" I love excel")
'Result is: "I love excel"
Msgbox WorksheetFunction.Trim("I love excel ")
'Result is: "I love excel"
Msgbox Trim("I love excel ")
'Result is: "I love excel"
End Sub
Use VBA to add Trim Function in a Range
The Trim Worksheet function can be added in a Range using property .Formula:
Sub TrimExample_6()
ThisWorkbook.Worksheets("Sheet1").Range("B1").Formula = "=trim(A1)"
End Sub
LTrim Function
The LTrim function removes spaces only from the left side of the word:
Sub TrimExample_7()
MsgBox LTrim(" I love excel ")
'Result is: "I love excel "
MsgBox LTrim(" I love excel")
'Result is: "I love excel"
MsgBox LTrim("I love excel ")
'Result is: "I love excel "
MsgBox LTrim(" I love excel ")
'Result is: "I love excel "
MsgBox LTrim(" I love excel")
'Result is: "I love excel"
MsgBox LTrim("I love excel ")
'Result is: "I love excel "
End Sub
VBA Programming | Code Generator does work for you!
RTrim Function
The RTrim function removes spaces only from the right side of the word:
Sub TrimExample_8()
MsgBox RTrim(" I love excel ")
'Result is: " I love excel"
MsgBox RTrim(" I love excel")
'Result is: " I love excel"
MsgBox RTrim("I love excel ")
'Result is: "I love excel"
MsgBox RTrim(" I love excel ")
'Result is: " I love excel"
MsgBox RTrim(" I love excel")
'Result is: " I love excel"
MsgBox RTrim("I love excel ")
'Result is: "I love excel "
End Sub
Trim, Ltrim and Rtrim do not remove spaces between words.
Remove all spaces from text
Trim will only remove extra spaces in between words, but to remove all spaces in a string of text, you can use the Replace Function:
Sub ReplaceExample ()
MsgBox Replace(" I love excel ", " ", "")
'Result is: "Iloveexcel"
End Sub
Are all your other functions leaving whitespace behind?
Get CleanUltra!
CleanUltra removes all whitespace and non-printable characters including whitespace left behind by other functions!
I hope you find this useful. Any improvements are welcome!
Function CleanUltra( _
ByVal stringToClean As String, _
Optional ByVal removeSpacesBetweenWords As Boolean = False) _
As String
' Removes non-printable characters and whitespace from a string
' Remove the 1 character vbNullChar. This must be done first
' if the string contains vbNullChar
stringToClean = Replace(stringToClean, vbNullChar, vbNullString)
' Remove non-printable characters.
stringToClean = Application.Clean(stringToClean)
' Remove all spaces except single spaces between words
stringToClean = Application.Trim(stringToClean)
If removeSpacesBetweenWords = True Then _
stringToClean = Replace(stringToClean, " ", vbNullString)
CleanUltra = stringToClean
End Function
Here’s an example of it’s usage:
Sub Example()
Dim myVar As String
myVar = " abc d e "
MsgBox CleanUltra(myVar)
End Sub
Here’s a test I ran to verify that the function actually removed all whitespace. vbNullChar
was particularly devious. I had to set the function to remove it first, before the CLEAN
and TRIM
functions were used to stop them from removing all characters after the vbNullChar
.
Sub Example()
Dim whitespaceSample As String
Dim myVar As String
' Examples of various types of whitespace
' (vbNullChar is particularly devious!)
whitespaceSample = vbNewLine & _
vbCrLf & _
vbVerticalTab & _
vbFormFeed & _
vbCr & _
vbLf & _
vbNullChar
myVar = " 1234" & _
whitespaceSample & _
" 56 " & _
"789 "
Debug.Print "ORIGINAL"
Debug.Print myVar
Debug.Print "Character Count: " & Len(myVar)
Debug.Print
Debug.Print "CLEANED, Option FALSE"
Debug.Print CleanUltra(myVar)
Debug.Print CleanUltra(myVar, False)
' Both of these perform the same action. If the optional parameter to
' remove spaces between words is left blank it defaults to FALSE.
' Whitespace is removed but spaces between words are preserved.
Debug.Print "Character Count: " & Len(CleanUltra(myVar))
Debug.Print
Debug.Print "CLEANED, Option TRUE"
Debug.Print CleanUltra(myVar, True)
' Optional parameter to remove spaces between words is set to TRUE.
' Whitespace and all spaces between words are removed.
Debug.Print "Character Count: " & Len(CleanUltra(myVar, True))
End Sub
I created a macro for removing all whitespace in a string, specifically an email address. However it only removes about 95% of the whitespace, and leaves a few.
My code:
Sub NoSpaces()
Dim w As Range
For Each w In Selection.Cells
w = Replace(w, " ", "")
Next
End Sub
Things I have tried to solve the issue include:
~ Confirmed the spaces are indeed spaces with the Code function, it is character 32 (space)
~ Used a substitute macro in conjuction with the replace macro
~ Have additional macro utilizing Trim function to remove leading and trailing whitespace
~ Made a separate macro to test for non-breaking spaces (character 160)
~ Used the Find and Replace feature to search and replace spaces with nothing. Confirmed working.
I only have one cell selected when I run the macro. It selects and goes through all the cells because of the Selection.Cells part of the code.
A few examples:
1 STAR MOVING @ ATT.NET
322 TRUCKING@GMAIL.COM
ALEZZZZ@AOL. COM.
These just contain regular whitespace, but are skipped over.
Excel VBA TRIM Function
VBA TRIM comes under the String and Text functions. This function is a Worksheet function in VBA. Similar to the worksheet reference, this function one may use to trim or remove unwanted spaces from a string. It takes a single argument, an input string, and returns an output as a string.
There are several situations where we download the data from online servers, and we face a situation of unorganized data and unwanted spaces in the cell. Dealing with unnecessary spaces is very painful to work with. So, in regular Worksheet functions, we have TRIM in excelThe Trim function in Excel does exactly what its name implies: it trims some part of any string. The function of this formula is to remove any space in a given string. It does not remove a single space between two words, but it does remove any other unwanted spaces.read more to eliminate “Leading Spaces, Trailing Spaces, and In-Between Space.” In VBA, we also have a TRIM function, which works the same as the Excel function, but there is only one slight difference. We will see that in this article a little later.
Table of contents
- Excel VBA TRIM Function
- What Does Trim Function Do?
- Syntax
- Examples
- Example #1
- Example #2
- Example #3 – Clean the Data in Cells
- Difference Between Excel & VBA Trim Function
- Things to Remember
- Recommended Articles
- What Does Trim Function Do?
You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA TRIM (wallstreetmojo.com)
What Does Trim Function Do?
TRIM is a string function that removes spaces in excelWhile importing or copy-pasting the data from an external source, extra spaces are also copied in Excel. This makes the data disorganized and difficult to be used. The purpose of removing unwanted spaces from the excel data is to make it more presentable and readable for the user.
read more from the selected cell. For example, in space, we have three types: Leading Space, Trailing Space, and In-Between Space.
Leading Space is nothing, but before any value starts in the cell, if there is any space, then it is called Leading Space.
Trailing Space is nothing, but after the end of the value in the cell, if there is any space, it is called Trailing Space.
In-Between Space is nothing after the end of each word. Ideally, we should have one space character. Anything more than one space character is known as In-Between Space.
To overcome all these problems, we have a function called TRIM.
Syntax
String: What is the string or value you want to trim? It could be a cell reference and a direct value supply to the formula.
Examples
You can download this VBA TRIM Function Template here – VBA TRIM Function Template
Example #1
Now, we will see how to remove leading spaces in excelThe TRIM function in Excel can remove all the unwanted spaces in the excel cell. read more using the TRIM function. Follow the below steps:
Step 1: Create a Macro name and declare a variable as String.
Code:
Sub Trim_Example1() Dim k As String End Sub
Step 2: Now, assign a value using the TRIM for this declared variable.
Code:
Sub Trim_Example1() Dim k As String k = Trim( End Sub
Step 3: For this String type, the word in double quotes is “Welcome to VBA.”
Code:
Sub Trim_Example1() Dim k As String k = Trim(" Welcome to VBA") End Sub
Step 4: Now, show the result of this variable in the message box.
Code:
Sub Trim_Example1() Dim k As String k = Trim(" Welcome to VBA") MsgBox k End Sub
Step 5: Run this code using the F5 key or manually. We should get the correct string in the message box.
Output:
So, the TRIM function removed all the leading spaces we had entered into the string value. Hence, the correct sentence, i.e., “Welcome to VBA.“
Example #2
Now, take a look at one more example to remove trailing spaces. Again, take the same word but this time, enter trailing spaces.
“Welcome to VBA. “
Code:
Sub Trim_Example2() Dim k As String k = Trim("Welcome to VBA ") MsgBox k End Sub
Run this code manually or through the F5 key Trim function removes trailing spaces.
Output:
Example #3 – Clean the Data in Cells
Now, we will see the practical example of cleaning the data in excel cells. Assume you have a data set like the one below in your Excel sheet.
We need to write different codes when we have more than one data cell. Follow the below steps to write code.
Step 1: Declare a variable as “Range.”
Code:
Sub Trim_Example3() Dim MyRange As Range End Sub
Step 2: Since the Range data type is an object, we must set the range first. So, set the range as “selection.”
Code:
Sub Trim_Example3() Dim MyRange As Range Set MyRange = Selection End Sub
Note: MyRange = Selection means whatever the cells we select becomes a range. So in that range, TRIM removes unwanted spaces.
Step 3: Now, apply the TRIM function using For Each VBA LoopA VBA loop in excel is an instruction to run a code or repeat an action multiple times.read more.
Code:
Sub Trim_Example3() Dim MyRange As Range Set MyRange = Selection For Each cell In MyRange cell.Value = Trim(cell) Next End Sub
Step 4: Now, go back to the worksheet. Go to insert and draw a rectangular shape.
Step 5: Add a word to the inserted rectangular shape as click here to clean the data.
Step 6: Right-click on the rectangular shape and select the assigned Macro.
Step 7: Now, the Macro names box will open. Select the name of the Macro we just created. Then, click on “OK.”
Step 8: Now, select the range where we need to clean the data.
Step 9: After selecting the range, click on the assigned Macro rectangular box. It will clean the data.
So, we got cleaned value, i.e., after removing leading and trailing spaces.
Difference Between Excel & VBA Trim Function
The only difference between them is that the VBA function cannot remove in between spaces while the worksheet function in VBAThe worksheet function in VBA is used when we need to refer to a specific worksheet. When we create a module, the code runs in the currently active sheet of the workbook, but we can use the worksheet function to run the code in a particular worksheet.read more does. For example, take a look at the below example.
In cell A3, we have in-between spaces. However, selecting and clicking on the rectangular shape will only remove trailing and leading spaces, not in-between spaces.
To overcome this problem, we need to use the Trim function as a worksheet function in the code.
Code:
Sub Trim_Example3() Dim MyRange As Range Set MyRange = Selection For Each cell In MyRange cell.Value = WorksheetFunction.Trim(cell) Next End Sub
Here we have used a worksheet function, not a VBA functionVBA functions serve the primary purpose to carry out specific calculations and to return a value. Therefore, in VBA, we use syntax to specify the parameters and data type while defining the function. Such functions are called user-defined functions.read more. It will remove all kinds of spaces.
Things to Remember
- VBA Trim and Worksheet Trim syntax are the same.
- It can only remove leading and trailing spaces, not in-between spaces.
- The Excel Trim function can remove all kinds of spaces.
Recommended Articles
This article has been a guide to VBA TRIM Function. Here, we learn how to use the TRIM function to remove spaces such as leading and trailing, with practical examples and a downloadable Excel template. Below you can find some useful Excel VBA articles: –
- Excel VBA String Functions
- VBA DIR Function
- FIND Function in VBA
- Cell References in VBA