excel - 可变前导零(数字格式)
问题描述
如果我在 A 列中有一个从 1 到 1000 的值列表,我该如何格式化该列,以便每个值都是“0000”,即。基于 len(max(A:A)) 这将是 4。这将需要取决于最大值。
如果 A 列中的最大值为 10,500,我希望每个值的格式都为“00000”。有什么方法可以自动设置它 - 无论是在 VBA 中还是在其他格式化方法中?谢谢
解决方案
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")
推荐阅读
- azure - 如何在 Kusto 时间表上缩放数据系列
- sql - 分区而不重新排序数据
- c# - 输入的标记助手 [asp-for] 不适用于字节的数组值(与 @Html.HiddenFor 相对)
- masstransit - 无法使用 Masstransit.Integration.AspNetCore 注册传奇
- android - Android Paging 库不适用于异步请求
- docker - Stikked Docker 容器 - 禁用验证码
- python - 使用 keras 自定义过滤器 CNN
- jquery - 我怎样才能使这个中心在页面中间?
- python - Python 类型提示:如何在整个项目范围内强制执行?
- makefile - 为什么make会将一个文件复制到另一个文件上?(目标取决于整个文件夹。)