可变前导零(数字格式)

chi*_*t12 1 excel vba

如果我在 A 列中有一个范围从 1-1000 的值列表,我该如何格式化该列,使每个值都是“0000”,即。基于 len(max(A:A)) ,该值为 4。这需要取决于最大值。

如果 A 列中的最大值为 10,500,我希望每个值的格式为“00000”。有什么方法可以自动设置它 - 无论是在 VBA 还是其他格式化方法中?谢谢

Pᴇʜ*_*Pᴇʜ 5

Option Explicit

Public Sub example()
    ' define the location/column
    Dim Location As Range
    Set Location = ThisWorkbook.Worksheets("Sheet1").Range("A:A")
    
    ' get the amount of digits the maximum number has
    Dim Digits As Long
    Digits = Len(CStr(Application.WorksheetFunction.Max(Location)))
    
    ' set the number format of the location to the amount of digits
    Location.NumberFormat = String(Digits, "0")
    
End Sub
Run Code Online (Sandbox Code Playgroud)

或者甚至更好地编写一个可以在任何范围内重复使用的通用过程:

Option Explicit

Public Sub SetNumberFormatToMaxDigits(ByVal Location As Range)
    Dim Digits As Long
    Digits = Len(CStr(Application.WorksheetFunction.Max(Location)))
    
    Location.NumberFormat = String(Digits, "0")
End Sub
Run Code Online (Sandbox Code Playgroud)

就这样称呼它

SetNumberFormatToMaxDigits ThisWorkbook.Worksheets("Sheet1").Range("A:A")
Run Code Online (Sandbox Code Playgroud)