VBA to check if one two dates are consecutive years

swapnilk

Board Regular
Joined
Apr 25, 2016
Messages
75
Office Version
  1. 365
  2. 2021
Platform
  1. Windows
Hi,

I have made a UserForm to collect data and based on the user input want to check whether two dates are consecutive years. Here is the code:

VBA Code:
Private Sub Submit_Click()

Dim ws As Worksheet

Set ws = Worksheets("MasterData")

ws.Range("E12").Value = CurrentDate.Value 'this date will be in 31/03/YYYY format
ws.Range("E14").Value = PrevDate.Value  'this date will be in 31/03/YYYY format

After above code i want to check whether dates in E12 and E14 are two dates wherein only year has changed (the DD/MM will always be 31/03 only YYYY can change)
For e.g. E12 = 31/03/2022 and E14=31/03/2021
If they are consecutive years then E13=E14 else E13=E14 + 1 year (i.e. 31/03/YYYY + 1 YYYY)

After that

VBA Code:
If ws.Range("E14").Value = ws.Range("E13").Value Then
Else
Sheets("StartUp1").Visible = True
Sheets("StartUp").Visible = False
Sheets("Data1").Visible = True
Sheets("Data").Visible = False
End Sub

Can someone please help me with the code for the middle part i.e. to check if dates are two consecutive years or not.
 

Excel Facts

Copy PDF to Excel
Select data in PDF. Paste to Microsoft Word. Copy from Word and paste to Excel.
You can use the VBA 'Year' function, e.g.

VBA Code:
    If Abs(Year(MyDate1) - Year(MyDate2) <= 1) Then
        'do something
    Else
        'do something else
    End If
 
Upvote 0
IMO, the logic is to subtract and compare as required. If that means using ranges, then like
If Year(sheets("Sheet5").range("A23"))-Year(Sheets("Sheet3").Range("A21") = 1 Then
 
Upvote 0

Forum statistics

Threads
1,214,918
Messages
6,122,255
Members
449,075
Latest member
staticfluids

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top