这是由Dammer15发布的,这正是我要找的。但是我需要它遍历整个列。我会直接问,但我还不能发表评论。
Dim My_Number As String
Dim i As Integer
My_Number = Range("AJ")
For i = 1 To Len(My_Number) - 1
If InStr(1, My_Number, "0") = 1 Then
My_Number = Right(My_Number, Len(My_Number) - 1)
Else
Range("AJ") = My_Number
Exit For
End If
Next
答案 0 :(得分:2)
您需要遍历每个值。我建议将整个范围上传到数组中,然后循环遍历:
Sub foo()
Dim rng As Range
Dim i As Long, j As Long
Dim arr() As Variant
Dim lastRow As Long
With ActiveSheet
lastRow = .Cells(.Rows.Count, "AJ").End(xlUp).Row
Set rng = .Range("AJ1", .Cells(lastRow, "AJ"))
arr = rng.Value
For i = LBound(arr, 1) To UBound(arr, 1)
My_Number = arr(i, 1)
For j = 1 To Len(arr(i, 1)) - 1
If Mid(arr(i, 1), j, 1) <> 0 Then
arr(i, 1) = Right(arr(i, 1), Len(arr(i, 1)) - (j - 1))
Exit For
End If
Next j
Next i
rng.Value = arr
End With
End Sub
答案 1 :(得分:1)
您可以使用正则表达式匹配前导0而不是您目前拥有的庞大替换功能:
Sub TestRe()
Dim LastCell As Range: Set LastCell = ActiveSheet.Columns("AJ").Find("*", SearchDirection:=xlPrevious)
Dim Rng As Range: Set Rng = ActiveSheet.Range("AJ1", LastCell)
Dim Cell As Range: For Each Cell In Rng
Cell.Value = RemoveLead0s(Cell.Value)
Next Cell
End Sub
Function RemoveLead0s(AlphaNum As String) As String
RemoveLead0s = AlphaNum
' RegExp requires "Microsoft VBScript Regular Expressions 5.5" reference
Dim RegEx As New RegExp
With RegEx
.Pattern = "^0*"
If .test(AlphaNum) Then RemoveLead0s = .Replace(AlphaNum, "")
End With
End Function