如果在Now()之前2天或者Now()之后2天的if值声明

我如何编码一个If语句,如果datereconcile范围内的值在当前date的2天之内,会提示msgbox?

 Sub upcoming_alert() Dim qw As Variant Dim datereconcile As Range Dim DATEROW As Long Dim nowpos2, nowneg2 As Long Set wb = ThisWorkbook Set datereconcile = wb.Sheets(1).Range("H:H") DATEROW = datereconcile(datereconcile.Cells.Count).End(xlUp).Row ' Get last filled cell Set datereconcile = Range(datereconcile(1), datereconcile(DATEROW)) ' Reduce rng size nowpos2 = Date - 2 nowneg2 = Date - 1 For Each qw In datereconcile If qw.Value >= nowpos2 Then MsgBox ("Date drop upcoming") End If Next End Sub 

我只是稍微修改你的代码。 我更喜欢使用简单的For循环,并使用整型variables而不是For Each qw In datereconcile (首选项和更快的解码)。 下面的macros将采取列H(8)中的所有单元格,并从第1行到第n行。 然后它会查看date值并将其与今天的date进行比较。 如果date在今天的两天之内,它将在debugging控制台(在VBA编辑器中Ctrl + G)中打印date。 如果需要,可以用警报functionreplace它。

编辑

添加了IsDate检查,以确保如果string存储而不是在H列date将不会有错误。

macros

 Sub upcoming_alert() 'Dimensions all variables Dim wb As Workbook Dim lastRow As Integer Dim daySpan As Integer Dim Ro As Integer Dim Co As Integer 'the date column in numerical format (represents column H) Co = 8 'Creates a reference to the parent of all child objects inside of the WITH clause With ThisWorkbook 'Determines the last date in the given column lastRow = .Sheets(1).Cells(.Sheets(1).Rows.Count, Co).End(xlUp).Row 'The number of days you want to "look around" from today's date daySpan = 2 'Loops through all the rows in the For Ro = 1 To lastRow 'Checks to make sure the given cell's value is a date and not a string If IsDate(CDate(.Sheets(1).Cells(Ro, Co))) Then 'Casts the give value in the cell as a date (CDate) 'Subtracts today's date from the current value 'Takes the absolute value and compares it to daySpan (2 by default) as a "2 day lookaround" If Abs(CDate(.Sheets(1).Cells(Ro, Co)) - Date) <= daySpan Then 'removed the alert because I didn't want to have to hit enter a bunch of times 'DO SOMETHING IN HERE Debug.Print .Sheets(1).Cells(Ro, Co) End If End If Next End With End Sub