Get Previous Year using VBA Functions

VBA Get Previous Year

Get Previous Year from Today’s Date and specified date using Excel VBA Functions. Year plays an important major role as part of date. It helps in data analysis to summarize data, to create graphs and dashboards. We also format year using format function in two ways either two year digit(xx) or four year digit(xxxx).

VBA Previous Year from specified Date:

Let us see the procedure how to get name of the year from today’s date using Year and DateAdd function.

'Procedure to find Previous Year From specified Date
Sub VBA_Previous_Year_From_Specified_Date()
    
    'Variable declaration
    Dim iYear As Integer
    
    'Retrieve Year from date
    iYear = DateAdd("y", -1, Year("01/01/2020"))
    
    'Display Year
    MsgBox "If specified date is '01/01/2020' then" & vbCrLf & _
    "Previous Year is : " & iYear, vbInformation, "Previous Year From Date"
    
End Sub

Here is the output screen shot of the above macro procedure.
VBA Previous Year

VBA Previous Year from Today’s Date:

Let us see the procedure how to get name of the year from today’s date using Date, Year and DateAdd functions.

'Procedure to find Previous Year From today's Date
Sub VBA_Previous_Year_From_Todays_Date()
    
    'Variable declaration
    Dim iYear As Integer
    
    'Retrieve Year from date
    iYear = DateAdd("y", -1, Year(Date))
    
    'Display Year
    MsgBox "If today's date is " & Date & " then" & vbCrLf & _
    "Previous year is : " & iYear, vbInformation, "Previous Year From Date"
    
End Sub

Let us see the output screenshot of the above macro procedure for your reference.
VBA Previous Year

Explanation: In the above procedures you can see Date, Year and DateAdd VBA functions. Here date displays date. Year function helps to display year from date.

Format Year of date:

We have different format methods to format year. You can find output in an immediate window.

'Format Year from date
Sub VBA_Format_Year()
    
    'Variable declaration
    Dim iYear As Integer
        
    iYear = Format("01/01/2018", "yy")
    Debug.Print iYear
    
    iYear = Format("01/01/2018", "yyyy")
    Debug.Print iYear
        
End Sub

Output Screenshot: Here is the output screenshot.
VBA Get Next Year

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays VBA Text Files VBA Tables

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers Blog

Leave a Comment