Formatting a number to two digits, even if the first is 0 vba

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 who have a problem with this are 1-9, which I would like to show as 01, 02, 03, etc. Is there any way to accomplish this?

+8
source share
3 answers

You cannot format an integer variable, you need to use a string variable to format it.

You can convert the day part of the date to leading zeros using the Day function to extract the day number from the date, and then use the Format function with the "00" format to add leading zero if necessary

Format (day (myDate), "00")

myDate is a Date variable containing the full date value

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 
+16
source

I did it like this:

 number_item = 2 number_item = WorksheetFunction.Text(number_item, "00") 

This will complete the task.

+1
source

Of course, you can format an integer, you just convert it to a string in the format command:

 formattedIntAsString = Format(Cstr(intValue), "00") 
0
source

Source: https://habr.com/ru/post/981192/


All Articles