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