In VB6, the Trim() function trims spaces off the front and back of a string. I am wondering if there is a function that will trim not just spaces, but all whitespace (tabs in this case) off of each end of a string.
TrimAll: Removes all leading/trailing spaces, tabs, and any other character specified.
trim() The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.)
Trim() Removes all leading and trailing white-space characters from the current string.
I use this function:
Private Function TrimAll(Text As String) As String
Const toRemove As String = " " & vbTab & vbCr & vbLf 'what to remove
Dim s As Long: s = 1
Dim e As Long: e = Len(Text)
Dim c As String
If e = 0 Then Exit Function 'zero len string
Do 'how many chars to skip on the left side
c = Mid(Text, s, 1)
If c = "" Or InStr(1, toRemove, c) = 0 Then Exit Do
s = s + 1
Loop
Do 'how many chars to skip on the right side
c = Mid(Text, e, 1)
If e = 1 Or InStr(1, toRemove, c) = 0 Then Exit Do
e = e - 1
Loop
TrimAll = Mid(Text, s, (e - s) + 1) 'return remaining text
End Function
Usage:
Debug.Print "|" & TrimAll("") & "|" 'prints ||
Debug.Print "|" & TrimAll(" ") & "|" 'prints ||
Debug.Print "|" & TrimAll("a") & "|" 'prints |a|
Debug.Print "|" & TrimAll("a ") & "|" 'prints |a|
Debug.Print "|" & TrimAll(" a") & "|" 'prints |a|
Debug.Print "|" & TrimAll(" a b ") & "|" 'prints |a b|
Debug.Print "|" & TrimAll(vbTab & " " & "Some " & vbCrLf & " text. " & vbCrLf & " ") & "|" 'prints |Some
text.|
You can simply add the chars to be removed at the toRemove string.
It does not copy the partialy trimmed string again and again, but rather searches where the trimmed string starts and ends, and returns that portion only.
You'll have to combine the Trim
function with the Replace
function:
s = " ABC " & vbTab & " "
MsgBox Len(s)
MsgBox Len(Trim$(s))
s = Replace$(Trim$(s), vbTab, "")
MsgBox Len(s)
Note: The above code will also remove embedded tabs. Probably can resolve this with regular expressions but here's a way to trim spaces/tabs only from the ends via looping:
Dim s As String, char As String, trimmedString As String
Dim x As Integer
s = " " & vbTab & " ABC " & vbTab & "a " & vbTab
'// Trim all spaces/tabs from the beginning
For x = 1 To Len(s)
char = Mid$(s, x, 1)
If char = vbTab Or char = " " Then
Else
trimmedString = Mid$(s, x)
Exit For
End If
Next
'// Now do it from the end
For x = Len(trimmedString) To 1 Step -1
char = Mid$(trimmedString, x, 1)
If char = vbTab Or char = " " Then
Else
trimmedString = Left$(trimmedString, x)
Exit For
End If
Next
You should end up with ABC{space}{space}{tab}a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With