Excel VBA - compare date in cell to current date

44,713

Solution 1

Thanks to Dave and MiVoth I did :

Dim xdate As Date  
xdate = Worksheets("sheet1").Range("A1")  
   If Month(Date) = Month(xdate) And Year(Date) = Year(xdate) Then  
      MsgBox "OK"  
   Else  
      MsgBox "not OK"  
   End If  

That did the job!
Thank a lot to everyone,
Gadi

Solution 2

Does this help you:

Public Sub test()
    d = Sheet1.Range("A1")
    n = Now()
    If Year(d) = Year(n) And Month(d) = Month(n) Then
        MsgBox "It works"
    End If
End Sub

Solution 3

How about this:

Function MonthYear() As Boolean
MonthYear = False
If Not IsDate(Cells(1, 1)) Then Exit Function
If Month(Date) = Month(Cells(1, 1)) And Year(Date) = Year(Cells(1, 1)) Then
    MonthYear = True
End If
End Function

The function returns true if month and year are the same as current date. If not it returns false.

Share:
44,713
gadi
Author by

gadi

Sea-Kayaking is my passion, especially when the sea is high and rough. The higher the better! I was: teacher, electrician, soldier, theatre-lights-man, gardener, restaurant owner and did lots of high-tech. I'm a computer dinosaur from the era of Main-Frames. I should be put in a museum... Currently I'm at home, developing an PHP Javascript web application. When it's done I'll sell it for zillions and go around the world in my kayak!!! I am an enthusiastic member of the Brights. (look it up). I am owned by a cat.

Updated on May 07, 2020

Comments

  • gadi
    gadi about 4 years

    (Excel 2010 VBA) I have a cell (A1) containing a date in the format of mmm-yy ("Custom" category). Foe example, if I enter 1/6/13 the cell shows June-13. That's fine. In my VB macro I need to check this date whether the month is the current month and whether the year is the current year. I don't care about the day.

  • jaysoncopes
    jaysoncopes about 9 years
    Make sure to select one as an answer and preferably upvote one or both to ensure others with similar questions can easily find the correct answer.