将数字格式化为两位数,即使第一个是 0 vba
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28016643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Formatting a number to two digits even if the first is a 0 vba
提问by Chad Portman
I would like to be able to use VBA to display any number between 1-24 as a 2 digit number. Obviously the only ones that have a problem with this are 1-9 which I would like displayed as 01, 02, 03, etc. Is there a way to perform this?
我希望能够使用 VBA 将 1-24 之间的任何数字显示为 2 位数字。显然,唯一有问题的是 1-9,我希望将其显示为 01、02、03 等。有没有办法执行此操作?
回答by DeanOC
You cannot format an integer variable, you need to use a string variable for formatting.
您不能格式化整数变量,您需要使用字符串变量进行格式化。
You can convert the day part of a date to a format with leading zeros using the Dayfunction to extract the day number from the date, and then using the Formatfunction with a "00"format to add a leading zero where necessary
您可以使用Day函数将日期的天部分转换为带前导零的格式以从日期中提取天数,然后使用Format带"00"格式的函数在必要时添加前导零
Format(Day(myDate), "00")
格式(天(我的日期),“00”)
myDate is a Date variable containing the full Date value
myDate 是一个包含完整日期值的日期变量
The following macro can be used as a working sample
以下宏可用作工作示例
Sub Macro1()
Dim myDate As Date
myDate = "2015-5-1"
Dim dayPart As String
dayPart = Format(Day(myDate), "00")
MsgBox dayPart
End Sub
回答by GFunk
I know it's old, but, to answer the question as clarified, I would use in the built in date formatting functionality.
我知道它很旧,但是,为了回答澄清的问题,我会在内置的日期格式功能中使用。
To modify DeanOC's answer:
修改 DeanOC 的回答:
Sub Macro1()
Dim dateDate As Date
Dim strDate As String
Dim strDay As String
dateDate = "2015-5-1"
strDate = Format(dateDate, "mm/dd/yy") ' = "05/01/15"
strDay = Format(dateDate, "dd") ' = "01"
MsgBox "The two digit day of """ & strDate & """ is """ & strDay & ""."
End Sub
回答by Matti
I did it like this:
我是这样做的:
number_item = 2
number_item = WorksheetFunction.Text(number_item, "00")
This will do the job.
这将完成工作。
回答by PKatona
Sure you can format an integer, you just convert it to string within the format command:
当然你可以格式化一个整数,你只需在 format 命令中将它转换为字符串:
formattedIntAsString = Format(Cstr(intValue), "00")

