Excel VBA - 将单元格中的日期与当前日期进行比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17163982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Excel VBA - compare date in cell to current date
提问by gadi
(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.
(Excel 2010 VBA)我有一个单元格(A1),其中包含格式为 mmm-yy (“自定义”类别)的日期。例如,如果我输入 1/6/13,单元格会显示 June-13。没关系。在我的 VB 宏中,我需要检查这个日期是否月份是当前月份以及年份是否是当前年份。我不在乎那一天。
回答by Dave Sexton
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
回答by gadi
Thanks to Dave and MiVoth I did :
感谢 Dave 和 MiVoth 我做到了:
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
那做的工作!
非常感谢大家,
加迪
回答by MiVoth
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.
如果月份和年份与当前日期相同,则该函数返回 true。如果不是,则返回 false。