简体   繁体   中英

Excel VBA Union Rows with date value >= Date

I am trying to write a macro that populates an email with rows in a range if the date cell (column H) in the row is greater than or equal to the current date.

The below code populates an email with seemingly random rows.

Dim rng As Range
Dim row As Range
Dim rng2 As Range

Set rng = Range("B52:I79")

For Each row In rng.Rows
    If row.Columns("H") >= Date Then
        If Not rng2 Is Nothing Then
            Set rng2 = Union(rng2, row)
        Else
            Set rng2 = row
        End If
    End If
Next

Any help would be great!

Since your range starts from column B, if your date is in column H then you need to refer to it as column G as below:

Dim rng As Range
Dim row As Range
Dim rng2 As Range

Set rng = Range("B52:I79")

For Each row In rng.Rows
    If row.Columns("G") >= Date Then
        If Not rng2 Is Nothing Then
            Set rng2 = Union(rng2, row)
        Else
            Set rng2 = row
        End If
    End If
Next

Instead of refering to columns with letters in a range, use numbers. That way they are more obvious relatively.

range from b to i with column h is actually going to return i... call it column 7 though and you get less confusing results.

Also, to debug this, step through your code and send the match results to a variable in addition to the the union command.

That way you can see in your locals window each time it matches and you can ensure that the info that you want to match on is the info that is being matched on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM