How to use TimeSerial function in VBA?

In VBA (Visual Basic for Applications), the TimeSerial function returns a Variant of subtype Date for a specified hour, minute, and second. This function is handy when you need to create a time value within your code.

Basic syntax


TimeSerial(hour, minute, second)

  • hour: The hour value (0 through 23).
  • minute: The minute value (0 through 59).
  • second: The second value (0 through 59).



Sub DemonstrateTimeSerial()
    ' Declare a variable to hold the time.
    Dim someTime As Date
    ' Use the TimeSerial function to create a time value.
    someTime = TimeSerial(14, 30, 0) ' This will create a time equivalent to 2:30:00 PM.
    ' Display the created time in a message box.
    MsgBox "The created time is: " & Format(someTime, "hh:mm:ss AM/PM")
End Sub

In this example, the TimeSerial function is used to create a time value representing 2:30 PM. The Format function is then used to format the time as a string in a 12-hour format with an AM/PM specifier, which is then displayed in a message box.

Remember that the TimeSerial function will handle overflow. If you specify a value outside the usual range for hours, minutes, or seconds, it will calculate the time accordingly. For example, TimeSerial(25, 0, 0) will be interpreted as 1:00 AM the next day.

To run the above VBA code, you would typically insert it into a VBA module in an Excel workbook via the Microsoft Visual Basic for Applications editor, which you can access by pressing ALT + F11 in Excel. Then you can run the procedure by pressing F5 while the cursor is inside the procedure or by attaching the subroutine to a form button or other control.

Unlock Your Potential


Basic - Advanced


Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project

Leave a Reply

Your email address will not be published. Required fields are marked *