How to remove spaces in between text?

后端 未结 10 573
日久生厌
日久生厌 2021-01-13 00:00

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

相关标签:
10条回答
  • 2021-01-13 00:44

    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
    
    0 讨论(0)
  • 2021-01-13 00:45

    My related issue was that the last character was a chr(160) - a non-breaking space. So trim(replace(Str,chr(160),"")) was the solution.

    0 讨论(0)
  • 2021-01-13 00:46

    Trim removes extra spaces at start and end, not in the middle of a string.

    Function CleanSpace(ByVal strIn As String) As String
        strIn = Trim(strIn)
    
      ' // Replace all double space pairings with single spaces
        Do While InStr(strIn, "  ")
            strIn = Replace(strIn, "  ", " ")
        Loop
    
        CleanSpace = strIn
    End Function
    

    From here.

    PS. It's not the most efficient way to remove spaces. I wouldn't use on many, very long strings or in a tight loop. It might be suitable for your situation.

    0 讨论(0)
  • 2021-01-13 00:50

    If You are familiar with collections, i once wrote a quick code that process the whole sheet even if it is huge and remove all double spaces, lead and trail spaces and invisible characters from all cells. Just take care it will remove the format of your text, i also did not do much testing and it's exhaustive but it worked for my short task and worked fast.

    This is an Auxiliary function that loads the sheet into a collection

    Function LoadInCol() As Collection
    
    Dim currColl As Collection
    Dim currColl2 As Collection
    
    Set currColl = New Collection
    Set currColl2 = New Collection
    
    With ActiveSheet.UsedRange
        LastCol = .Columns(.Columns.Count).Column
        lastrow = .Rows(.Rows.Count).Row
    End With
    
    For i = 1 To lastrow
    
        For j = 1 To LastCol
            currColl.Add Cells(i, j).Value
        Next
    
        currColl2.Add currColl
        Set currColl = New Collection
    
    Next
    
        Set LoadInCol = currColl2
    
    End Function
    

    And this is the main Sub that removes the spaces

    Sub RemoveDSpaces()
    
    'Removes double spaces from the whole sheet
    
    Dim Col1 As Collection
    Dim Col2 As Collection
    Dim Col3 As Collection
    
    Dim StrIn As String
    
    Dim Count As Long
    
    Set Col1 = New Collection
    Set Col2 = New Collection
    Set Col3 = New Collection
    
    
    Set Col1 = LoadInCol()
    
    Count = Col1.Count
    
    i = 0
    
    For Each Item In Col1
    
    i = i + 1
    If i >= Count + 1 Then Exit For
    
        Set Col2 = Item
    
        For Each Item2 In Col2
    
            StrIn = WorksheetFunction.Clean(Trim(Item2))
    
            Do Until InStr(1, StrIn, "  ", vbBinaryCompare) = 0
                StrIn = Replace(StrIn, "  ", Chr(32))
            Loop
    
            Col3.Add StrIn
    
        Next
    
    Col1.Remove (1)
    Col1.Add Col3
    Set Col3 = New Collection
    
    Next
    
    'Store Results
    
    Cells.ClearContents
    
        Z = 1
        m = 1
        Set Col3 = New Collection
    
        For Each Item In Col1
    
            Set Col3 = Item
    
                For Each Item2 In Col3
                    Cells(Z, m) = Item2
                    m = m + 1
                Next
    
                m = 1
                Z = Z + 1
    
        Next
    
    End Sub
    
    0 讨论(0)
提交回复
热议问题