VBA Format Time

Written by

Editorial Team

Reviewed by

Steve Rynearson

Last updated on July 19, 2021

This tutorial will demonstrate how to use the Format VBA function to format time.

Format Function and Time

VBA Format Time with Predefined Formats

The VBA Format function can be used to convert a number to a string with a predefined format. The available formats for time are long time, medium time, and short time.

Sub FormatTimeExample_1()
Dim DateEx As Date

DateEx = #4/18/2020 6:05:07 PM#
MsgBox Format(DateEx, "Long Time")      'Result is: 6:05:07 PM
MsgBox Format(DateEx, "Medium Time")    'Result is: 06:05 PM
MsgBox Format(DateEx, "Short Time")     'Result is: 18:05

DateEx = #2/18/2021 6:05:07 AM#
MsgBox Format(DateEx, "Long Time")      'Result is: 6:05:07 AM
MsgBox Format(DateEx, "Medium Time")    'Result is: 06:05 AM
MsgBox Format(DateEx, "Short Time")     'Result is: 06:05

End Sub

VBA Format Time with Custom Formats

The VBA Format function can be used to convert a number to a string with custom formats. Symbols h and hh are used for hours, n and nn for minutes, s and ss for seconds, ttttt for full time according to system settings and AM/PM, am/pm, A/P, a/p, AMPM for the am-pm system.

Sub FormatTimeExample_2()
Dim DateEx As Date
DateEx = #4/18/2020 6:05:07 PM#

MsgBox Format(DateEx, "hh:nn:ss")     'Result is: 18:05:07
MsgBox Format(DateEx, "h:n:s AM/PM")  'Result is: 6:5:7 PM

MsgBox Format(DateEx, "h")             'Result is: 18
MsgBox Format(DateEx, "hh")            'Result is: 18
MsgBox Format(DateEx, "h:n")           'Result is: 18:5
MsgBox Format(DateEx, "hh:nn")         'Result is: 18:05
MsgBox Format(DateEx, "hh:nn:s")       'Result is: 18:05:7
MsgBox Format(DateEx, "hh:nn:ss")      'Result is: 18:05:07

MsgBox Format(DateEx, "\T\i\m\e\ \i\s\:\ hh:nn:ss")
'Result is: Time is: 18:05:07
End Sub

 

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro - A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users! vba save as


Learn More!
vba-free-addin

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

(No installation required!)

Free Download

Return to VBA Code Examples