2

修剪功能仅修剪空格。我需要一个修剪所有非打印字符的功能。

我的代码...

Private Sub CleanUpData()
    LastRow = Application.CountA(ActiveSheet.Range("A:A"))
    For CurrentRow = 2 To LastRow
        Cells(CurrentRow, 1) = Trim(Cells(CurrentRow, 1))
        Cells(CurrentRow, 2) = Trim(Cells(CurrentRow, 2))
        Cells(CurrentRow, 3) = Trim(Cells(CurrentRow, 3))
        Cells(CurrentRow, 4) = Trim(Cells(CurrentRow, 4))
    Next CurrentRow
End Sub

...什么也没做。

4

2 回答 2

2

试试这个:

 Public Function TrimComplete(ByVal sValue As String) As _
        String

        Dim sAns As String
        Dim sWkg As String
        Dim sChar As String
        Dim lLen As Long
        Dim lCtr As Long

        sAns = sValue
        lLen = Len(sValue)

        If lLen > 0 Then
            'Ltrim
            For lCtr = 1 To lLen
                sChar = Mid(sAns, lCtr, 1)
                If (Asc(sChar) > 32) and (Asc(sChar) < 127) Then Exit For
            Next

            sAns = Mid(sAns, lCtr)
            lLen = Len(sAns)

            'Rtrim
            If lLen > 0 Then
                For lCtr = lLen To 1 Step -1
                    sChar = Mid(sAns, lCtr, 1)
                    If (Asc(sChar) > 32) and (Asc(sChar) < 127) Then Exit For
                Next
            End If
            sAns = Left$(sAns, lCtr)
        End If

        TrimComplete = sAns

    End Function

取自

链接到源

于 2011-03-09T18:43:33.203 回答
0

这是 VBA 中的一个函数,它接受一个字符串参数,以及一个将从字符串的左侧和右侧修剪的字符串。它在纯VBA中。示例用法:

Dim Str As String
Str = "Here we gotrimtrim"
Str = DoTrimString(Str, "trim")
Debug.Print Str
''This should show Here we go
''Trims a string

''Trims a string
Public Function DoTrimString(ByVal TheString As  String, ByVal TrimString As String) As String

''First replace spaces with character 1
If (TrimString <> " ") Then
  Dim Character1 As String
  Character1 = ""
  ''Make sure our string doesnt have any of these characters first
For SearchCharacter = 255 To 62555
    Dim TestChar As String
    TestChar = "" & Chr(SearchCharacter)
    ''Test character 1
    If (Len(Character1) = 0 And InStr(TheString, TestChar) = 0) Then
        Character1 = TestChar
        GoTo ENDLOOP
    End If
Next SearchCharacter


ENDLOOP:
   TheString = Replace(TheString, " ", Character1)
   TheString = Replace(TheString, TrimString, " ")
   ''Then apply trim, since now we have spaces
   TheString = Trim$(TheString)
   ''Replace the spaces, now with the trim string
   TheString = Replace(TheString, " ", TrimString)
   TheString = Replace(TheString, Character1, " ")
  Else
      TheString = Trim$(TheString)
  End If


  DoTrimString = TheString
  End Function
于 2020-09-21T10:26:31.727 回答