Get Previous Year using VBA Functions

VBA Get Previous Year

Get Previous Year from Date using VBA Functions

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 todays 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 use Macro:

  • Open Visual Basic Editor by clicking Alt +F11
  • Goto code window by clicking F7
  • Copy any of the above specified procedure or macro
  • Paste above copied code in code window
  • Run macro by clicking F5 or Run command
  • You can see ouput on the screen
  • Find specified output screenshot above.

Related VBA Functions used in this article:

We have used Date,Month,MonthName and Format VBA functions. Click on below specified links to learn more about VBA functions.

VBA Date Function VBA Year Function VBA Format Function VBA DateAdd Function




Leave a Comment

Your email address will not be published. Required fields are marked *