2017-02-27 60 views
1

這是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

你不能這樣做'My_Number = Range(「AJ」)'你將需要循環遍歷範圍並單獨查看每個單元格。但他們都是數字還是他們有字符串中的文字? –

+0

它是字母數字 – Noisewater

回答

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 
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