指定一个月或两个月后的日期省略年份(vba)

时间:2013-12-02 01:37:49

标签: vba

Sub Main()

Dim celltxt As String
Dim cell As Range
Dim cell2 As Range
For Each cell In Range("M1:M" & Range("M" & Rows.Count).End(xlUp).Row)
    If cell = DateAdd("m", 1, Left(Now, 10)) Then
          MsgBox "Cell matches 1 month from today at " & cell.Address
          With Selection.Font
         .Color = -16776961
         .TintAndShade = 0
         End With
End If
Next
    For Each cell In Range("M1:M" & Range("M" & Rows.Count).End(xlUp).Row)
    If cell = DateAdd("m", 2, Left(Now, 10)) Then
        MsgBox "Cell matches 2 month from today at " & cell.Address
    End If
Next

End Sub

我希望系统搜索指定一个月或两个月后的日期,例如。当我在2013年11月11日搜索时,实际上我想要在11/12(所有年份)的所有日期都可以搜索并以红色突出显示。 但现在我只能搜索11/12/2013数据,如何解决?

1 个答案:

答案 0 :(得分:1)

尝试独立检查日期和月份。

  

Sub Main()

     

Dim celltxt As String Dim cell As Range Dim cell2 As Range Dim   aMonthFromNow As Date

     

对于范围内的每个单元格(“M1:M”和范围(“M”和Rows.Count).End(xlUp).Row)

aMonthFromNow = DateAdd("m", 1, Now)



If Month(cell) = Month(aMonthFromNow) And Day(cell) = Day(aMonthFromNow) Then
      MsgBox "Cell matches 1 month from today at " & cell.Address
      With Selection.Font
     .Color = -16776961
     .TintAndShade = 0
     End With End If Next
For Each cell In Range("M1:M" & Range("M" & Rows.Count).End(xlUp).Row)
If cell = DateAdd("m", 2, Left(Now, 10)) Then
    MsgBox "Cell matches 2 month from today at " & cell.Address
End If Next
     

End Sub