[英]How to remove leading spaces and/or “/” or “\”
我是 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
首先,我想說盡量避免UsedRange
,但要找到一種方法來獲取您最后使用的行和列。 然后,我不會對Worksheet
object 進行大量調用,而是通過使用數組來遍歷 memory 中的值。
最后,您可以進行許多替換等。但也許在這里使用正則表達式並不合適。 只是為了靈感,我會寫下以下內容:
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
所以最后它會將清理后的數據讀回工作表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.