I have this piece of code that originally uses the replace function(VBA) to replace certain characters in a string or column field in MS Access. The code is in a module.
Trim only removes leading and trailing spaces from the beginning and end of your string. A simple solutions would be:
Public Function TrmSpace(RemoveSpace As String) As String
RemoveSpace = Replace(RemoveSpace, " ", " ")
RemoveSpace = Replace(RemoveSpace, " ", " ")
RemoveSpace = Replace(RemoveSpace, " ", " ")
RemoveSpace = Replace(RemoveSpace, " th", "th")
RemoveSpace = Replace(RemoveSpace, " TH", "th")
TrmSpace = RemoveSpace
End Function
That would remove gaps up to eight spaces. If your data has actual tab characters and not spaces you'd need to replace " " with vbTab & vbTab & vbTab & vbTab.
A single line of code to 'squeeze' any number of repeating spaces to a one space and another to remove the leading space for th
regardless of case, thus reducing the above to this:
Public Function TrmSpace(RemoveSpace As String) As String
TrmSpace = Replace$(Replace$(Replace$(RemoveSpace, Chr$(32), Chr$(32) & Chr$(22)), _
Chr$(22) & Chr$(32), vbNullString), Chr$(22), vbNullString)
TrmSpace = Replace$(TrmSpace, " th", "th", , , vbTextCompare)
End Function
Just to add to Jesse's answer. Instead of doing so many replaces you can simply do the following (with a reference to Excel):
Public Function TrmSpace(RemoveSpace As String) As String
RemoveSpace = Excel.Application.WorksheetFunction.Trim(RemoveSpace)
RemoveSpace = Replace(RemoveSpace," th","th",,,vbTextCompare)
TrmSpace = RemoveSpace
End Function
The excel function Trim
is different from the vbaTrim
. The excel Trim
removes all spaces that are at the beginning and end and also any double/triple/etc spaces in the string. Using vbTextCompare
in your replace function will make it so it doesn't matter what mix of "th" is, so you don't need to worry if it is "TH" or "tH" or "Th", etc.