How to remove spaces in between text?

后端 未结 10 799
日久生厌
日久生厌 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: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
    

提交回复
热议问题