Why trim is not working in VBA?
for i = 3 to 2000
activesheet.cells(i,\"C\").value = trim(Activesheet.cells(i,\"C\").value)
next i
It is un
The VBA Trim function is different than Excel's. Use Excel's Application.WorksheetFunction.Trim function instead.
Excel Trim will remove all spaces except a single space between words. VBA Trim will remove leading and trailing spaces.
Thank MS for using the same keyword for different functions.
I know this is quite old but thought I'd add in something else rather than all these replace options.
Using trim (or trim$) in VBA will remove the leading and trailing spaces, which as mentioned is different from =TRIM in Excel.
If you need to remove spaces (as mentioned below not necessarily all whitespace) from inside a string simply use WorksheetFunction.Trim
.
Sometimes what looks to be a space is not a space but a character that cannot be displayed. Use the ASC function to get the integer value of the character. Then use the following code:
Function CleanSpace(ByVal StrIn As String) As String
StrIn = Trim(StrIn)
' Searches string from end and trims off excess ascii characters
Dim StrLength As Integer
Dim SingleChar As Integer
Dim StrPosition As Integer
SingleChar = 1
StrLength = Len(StrIn)
StrPosition = StrLength - 1
Do Until Asc(Mid(StrIn, StrPosition, SingleChar)) <> 0
StrPosition = StrPosition - 1
Loop
StrIn = Mid(StrIn, 1, StrPosition)
End Function
I know this question is old but I just want to share my solution on how to deal and fix with this issue.
Maybe you might wondering why sometimes TRIM function
isn't working, remember that it will only remove spaces and spaces are equivalent to ASCII 32. So if these ASCII 13 or ASCII 10 exists in the Beginning or end of your string value then TRIM function
will not work on it.
Function checkASCIItoBeRemoved(myVal) As String
Dim temp As String
temp = Replace(Trim(myVal), Chr(10), Empty)
temp = Replace(temp, Chr(13), Empty)
checkASCIItoBeRemoved = temp
End Function
With this code it works for me, by the way if this might not work on your side then try to check the ASCII of you string value because it might have another invisible special char that might not covered on my code to replace on it, kindly add on it to work.
Please see reference for some invisible special char.
When you call Trim() VBA is actually calling Strings.Trim(). This function will only remove leading and trailing spaces. To remove excessive spaces within a string, use
Application.Trim()
I know this question is old but I just found it and thought I'd add what I use to remove multiple spaces in VBA....
cleanString = Replace(Replace(Replace(Trim(cleanString), _
" ", " |"), "| ", ""), " |", " ") 'reduce multiple spaces chr(32) to one