You can use the TimeValue function in VBA to return the time value from a given string.
Here is one common way to use this function in practice:
Sub GetTimeValue()
Dim i As Integer
For i = 2 To 7
Range("B" & i) = TimeValue(Range("A" & i))
Next i
End Sub
This particular macro will extract the time value from the datetimes in the range A2:A7 and return this time value in the corresponding range of B2:B7.
The following example shows how to use this syntax in practice.
Example: How to Use TimeValue Function in VBA
Suppose we have the following column of datetimes in Excel:
Suppose we would like to extract the time from each datetime in column A and display it in column B.
We can create the following macro to do so:
Sub GetTimeValue()
Dim i As Integer
For i = 2 To 7
Range("B" & i) = TimeValue(Range("A" & i))
Next i
End Sub
When we run this macro, we receive the following output:
Column B shows the time value for each datetime in column A.
For example:
- The TimeValue function returns 10:15:34 AM from 1/1/2023 10:15:34 AM
- The TimeValue function returns 12:34:18 PM from 1/3/2023 12:34:18 PM
- The TimeValue function returns 8:23:00 AM from 1/5/2023 8:23:00 AM
And so on.
Note: You can find the complete documentation for the TimeValue function in VBA here.
Additional Resources
The following tutorials explain how to perform other common tasks in VBA:
How to Compare Dates in VBA
How to Insert a Timestamp Using VBA
How to Format Time in VBA