Excel VBA - compare date in cell to current date

℡╲_俬逩灬. 提交于 2021-02-08 05:26:55

问题


(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.


回答1:


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



回答2:


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




回答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.



来源:https://stackoverflow.com/questions/17163982/excel-vba-compare-date-in-cell-to-current-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!