How to use Second function in VBA?

In VBA (Visual Basic for Applications), the Second function is used to obtain the seconds component of a given time. This function takes a single argument, which is the time value from which you want to extract the seconds. The returned value is an integer between 0 and 59.



Sub GetSecondsExample()
    ' Assume you have a time value in cell A1 (e.g., 1:23:45 PM)
    Dim myTime As Variant
    Dim seconds As Integer
    ' Assign the time value to a variable
    myTime = Range("A1").Value
    ' Use the Second function to get the seconds component
    seconds = Second(myTime)
    ' Display the seconds in a message box
    MsgBox "The seconds component is: " & seconds
End Sub

In this example, myTime is assigned the time value from cell A1, and then we use the Second function to retrieve the seconds component of that time. Finally, the seconds are displayed in a message box.

You can also directly pass a time value to the Second function, like so:


Sub DirectSecondExample()
    Dim seconds As Integer
    ' Using a direct time value
    seconds = Second("13:45:25")
    ' The result will be 25
    MsgBox "The seconds component is: " & seconds
End Sub

Remember to ensure that the time is properly formatted and recognized as a date or time by VBA to avoid errors.

To use the Second function with the current system time, you could do the following:


Sub GetCurrentSeconds()
    Dim currentTime As Date
    Dim currentSeconds As Integer
    ' Get the current system time
    currentTime = Now
    ' Extract the seconds component
    currentSeconds = Second(currentTime)
    ' Display the seconds
    MsgBox "The current seconds are: " & currentSeconds
End Sub

In this subroutine, Now is used to get the current date and time, and then the Second function gets the seconds component which is displayed in a message box.

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 *