VBA Function: Format
The VBA Format function returns a string based on a date or number in the specified format.
Usage:
Format(value, format)
Examples of Usage
Using the Format function to return the following values in different formats:
Sub example()
'98.1%
MsgBox Format(0.9814, "0.0%")
'54,321.90
MsgBox Format(54321.9, "##,##0.00")
'$54,321.90
MsgBox Format(54321.9, "$#,##0.00")
End Sub
Using the Format function to return the following date in different formats:
Sub example()
myDate = #05/04/2024 3:35:45 PM#
'05/04/24
MsgBox Format(myDate, "mm/dd/yy")
'May 4 2024
MsgBox Format(myDate, "mmmm d yyyy")
'Saturday
MsgBox Format(myDate, "dddd")
'05/04/2024 3:35 PM
MsgBox Format(myDate, "mm/dd/yyyy h:nn AM/PM")
'Saturday 4 at 3:35 PM
MsgBox Format(myDate, "dddd d at h:nn AM/PM")
End Sub
Date Formats
Table of different date formats usable with the Format function:
Characters | Example | Description |
---|---|---|
d | 8 | Day (1 to 31) |
dd | 08 | Day (01 to 31) |
ddd | Fri | Day of the week (abbreviated) |
dddd | Friday | Day of the week |
m | 1 | Month (1 to 12) |
mm | 01 | Month (01 to 12) |
mmm | Jan | Month (abbreviated) |
mmmm | January | Month |
yy | 24 | Year (last 2 digits) |
yyyy | 2024 | Year |
h | 9 | Hours (0 to 23) |
hh | 09 | Hours (00 to 23) |
n | 5 | Minutes (0 to 59) |
nn | 05 | Minutes (00 to 59) |
s | 7 | Seconds (0 to 59) |
ss | 07 | Seconds (00 to 59) |
AM/PM | AM | AM/PM |