VBA FORMATDATETIME Function (Syntax + Example)

puneet-gogia-excel-champs

- Written by Puneet

The VBA FORMATDATETIME function is listed under the data type conversion category of VBA functions. When you use it in a VBA code, it returns a string by applying a date and time format to it and returns it as a string. In simple words, when you apply an expression it can apply data and time format to it.

Syntax

FormatDateTime(Expression, [NamedFormat])

Arguments

  • Expression: The value that you want to format as a date.
  • [NamedFormat]: An vbDateTimeFormat enumeration to specify the format that you want to apply to the Expression.
    • vbGeneral: As per the system’s general date setting.
    • vbLongDate: As per the system’s Long Date settings.
    • vbLongTime: As per the system’s Long Time settings.
    • vbShortDate: As per the system’s Short Date settings.
    • vbShortTime: As per the system’s Short Time settings.

Example

To practically understand how to use the VBA FORMATDATETIME function, you need to go through the below example where we have written a vba code by using it:

example-vba-formatdatetime-function
Sub example_FORMATDATETIME()
Range("B1").Value = FormatDateTime(Range("A1"))
End Sub

In the above code, we have used the FORMATDATETIME to convert the value in the cell A1 into a valid date and time value (as per VBA) and returned the result in cell B1.

Notes

  • If the value specified is a value other than a date and time or a string that can’t be recognized as a date and time, VBA will return the run-time 13 error.
Last Updated: June 22, 2023