1

我是 Excel 中的 VBA 新手。我有一个始终有 172 列的电子表格。答:FP。它可能有 2 到多行。对于电子表格中的每个单元格,我想删除所有前导和尾随空格以及任何前导或尾随“/”或“\”。字符串可以包含反斜杠或正斜杠,但不能在字符串的开头或结尾。我的代码删除了前导和尾随空格。它删除尾随的反斜杠或正斜杠。但是,它不会删除前导斜杠。我不明白为什么。有没有更好的方法来实现我的目标?谢谢您的帮助。

For Each Rng In ActiveSheet.UsedRange
   CellVal = Trim(Rng.Value)
   LengT = Trim(Len(CellVal))

      If CellVal <> "" Then
         If Not Rng.HasFormula Then
            While Trim(Left(CellVal, 1) = Chr(47)) Or Trim(Left(CellVal, 1) = Chr(92)) Or Trim(Right(CellVal, 1) = Chr(47)) Or Trim(Right(CellVal, 1) = Chr(92))

            If Trim(Left(CellVal, 1) = Chr(47)) Or Trim(Left(CellVal, 1) = Chr(92)) Then
               CellVal = Trim(Mid(CellVal, 2, LengT))
            ElseIf Trim(Right(CellVal, 1) = Chr(47)) Or Trim(Right(CellVal, 1) = Chr(92)) Then
               LengT = Len(CellVal)
               CellVal = Trim(Left(CellVal, LengT - 1))
               Rng.Value = CellVal
               LengT = LengT - 1
            End If
         Wend
      End If
   End If
Next Rng
4

1 回答 1

0

首先,我想说尽量避免UsedRange,但要找到一种方法来获取您最后使用的行和列。然后,Worksheet我不会对对象进行大量调用,而是通过使用数组来遍历内存中的值。

最后,您可以进行许多替换等。但也许在这里使用正则表达式并不合适。只是为了灵感,我会写下以下内容:

Sub Test()

Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Sheet1")
Dim lr As Long, lc As Long, x As Long, y As Long
Dim arr As Variant
Dim RegEx As Object: Set RegEx = CreateObject("vbscript.regexp")

'Set up regular expression first
RegEx.Global = True
RegEx.Pattern = "^[ \/\\]*(.*?)[ \/\\]*$"

With ws
    lr = .Cells(.Rows.Count, 1).End(xlUp).Row
    lc = .Cells(1, .Columns.Count).End(xlToLeft).Column
    arr = .Range(.Cells(1, 1), .Cells(lr, lc)).Value
    For x = LBound(arr, 1) To UBound(arr, 1)
        For y = LBound(arr, 2) To UBound(arr, 2)
            If RegEx.Test(arr(x, y)) Then arr(x, y) = RegEx.Execute(arr(x, y))(0).submatches(0)
        Next
    Next
    .Range(.Cells(1, 1), .Cells(lr, lc)).Value = arr
End With

End Sub

所以最后它会将清理后的数据读回工作表。

正则表达式演示

于 2020-05-22T08:19:18.637 回答