In VBA (Visual Basic for Applications), the Year function is used to extract the year part from a given date. It returns an integer representing the year of the specified date.
Here’s how to use the Year function in VBA:
- Have a date, either hard-coded, from a cell in Excel, or from a variable in your code.
- Use the Year function with that date as the argument.
Example
VB
In this example, GetYearExample is a subroutine that sets exampleDate to December 31, 2023, and then uses the Year function to get the year part from it. The result, which is 2023, is displayed in a message box.
You can also use the Year function with dates stored in Excel cells:
Sub GetYearExample()
Dim exampleDate As Date
Dim theYear As Integer
exampleDate = #12/31/2023# ' Assign a specific date (December 31, 2023)
theYear = Year(exampleDate) ' Extract the year part from the date
MsgBox "The year is: " & theYear ' Display the year in a message box
End Sub
VB
When working with dates, ensure that your date variables are properly formatted as dates or that the cells you work with have valid dates, otherwise you may run into errors or unexpected results.
Sub GetYearExample()
Dim exampleDate As Date
Dim theYear As Integer
exampleDate = #12/31/2023# ' Assign a specific date (December 31, 2023)
theYear = Year(exampleDate) ' Extract the year part from the date
MsgBox "The year is: " & theYear ' Display the year in a message box
End Sub