首页 > 解决方案 > 可变前导零(数字格式)

问题描述

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

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

标签: excelvba

解决方案


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

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

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

就这样称呼它

SetNumberFormatToMaxDigits ThisWorkbook.Worksheets("Sheet1").Range("A:A")

推荐阅读