Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a number to two digits even if the first is a 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 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?

like image 771
Chad Portman Avatar asked Jan 19 '15 01:01

Chad Portman


People also ask

Does != Work in VBA?

Bookmark this question. Show activity on this post. The problem is that != does not work as a function in excel vba.


4 Answers

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 Day function to extract the day number from the date, and then using the Format function with a "00" format to add a leading zero where 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
like image 62
DeanOC Avatar answered Sep 25 '22 01:09

DeanOC


Sure you can format an integer, you just convert it to string within the format command:

formattedIntAsString = Format(Cstr(intValue), "00")
like image 43
PKatona Avatar answered Sep 26 '22 01:09

PKatona


I did it like this:

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

This will do the job.

like image 36
Matti Avatar answered Sep 23 '22 01:09

Matti


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:

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
like image 41
GFunk Avatar answered Sep 24 '22 01:09

GFunk