Trim all types of whitespace, including tabs

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


How about:

Private Declare Function lstrlen Lib "kernel32" Alias "lstrlenW" ( _
    ByVal lpString As Long) As Long

Private Declare Function StrTrim Lib "shlwapi" Alias "StrTrimW" ( _
    ByVal pszSource As Long, _
    ByVal pszTrimChars As Long) As Long

Private Function TrimWS(ByVal Text As String) As String
    'Unicode-safe.
    Const WHITE_SPACE As String = " " & vbTab & vbCr & vbLf

    If StrTrim(StrPtr(Text), StrPtr(WHITE_SPACE)) Then
        TrimWS = Left$(Text, lstrlen(StrPtr(Text)))
    Else
        TrimWS = Text
    End If
End Function

It is fast, and even faster if you use typelibs instead of Declare to define the API calls.


It's a shame there is no built in function. Here is the one I wrote. It does the trick.

Function TrimAllWhitespace(ByVal str As String)

    str = Trim(str)

    Do Until Not Left(str, 1) = Chr(9)
        str = Trim(Mid(str, 2, Len(str) - 1))
    Loop

    Do Until Not Right(str, 1) = Chr(9)
        str = Trim(Left(str, Len(str) - 1))
    Loop

    TrimAllWhitespace = str

End Function

Tags:

String

Vb6

Trim