How to hide rows in Excel based on values in two c

2019-08-31 04:21发布

First post here and i am very new to the world of Excel-VBA.

I am trying to automate some reports and have run into a little snag. i am trying to hide rows on an excel worksheet based on the value of cells in 2 seprate columns. i have given given an example below. (The real Document can contain up to 50 names at one given time and pretty much any date.)

For this example i would need to hide all rows that do not have the value JIM in column A and have a greater date than todays date in column B. (04/05/2014)

A       B
JIM     04/05/2014
JIM     04/05/2014
BOB     05/05/2014
BOB     04/05/2014
TED     07/05/2014
TED     04/05/2014
BOB     09/05/2014
JIM     04/05/2014
JIM     11/05/2014
TED     12/05/2014

I am using the below code at the minute but ran into some issues when adding a second argument.

Sub Delete_Name_Date()

Dim rng As Range, cell As Range

For Each cell In Range("A1:F15")
If cell.Value = "JIM" Then
cell.EntireRow.Hidden = False
Else: cell.EntireRow.Hidden = True

End If
Next


End Sub

Any help would be great.

Thanks

Adam

1条回答
做自己的国王
2楼-- · 2019-08-31 04:47

Try this one:

Sub Delete_Name_Date()
    Dim cell As Range

    For Each cell In Range("A1:A15")
        With cell
            .EntireRow.Hidden = _
                (.Value <> "JIM" And CDate(.Offset(, 1).Value) > Date)
        End With
    Next
End Sub

also for reliability I suggest you to use ThisWorkbook.Sheets("SheetName").Range("A1:A15") instead Range("A1:A15")

查看更多
登录 后发表回答