Vba Code to Hide or Unhide Rows Based on a Cell Value

Vba Code to Hide or Unhide Rows Based on a Cell Value

Heres my code, but its not really doing anything, I dont see anything wrong with it:

Private Sub PG1(ByVal Target As Range)
    If .Range("E50").Value = "Passed" Then
        Rows("51").EntireRow.Hidden = True
    End If
    ElseIf Range("E50").Value = "Failed" Then
        Rows("51").EntireRow.Hidden = True
    End If
End Sub

My intention is that when that specific cell in the previous row is set to "Passed" from the dropdown, then the below row would appear, if its a 'Failed" then it'll be hidden instead.

3 Answers

It looks like your code has some typos in it. You want something that is like this:

Sub PG1()

    If Range("E50").Value = "Passed" Then
        Rows("51:51").EntireRow.Hidden = True
    ElseIf Range("E50").Value = "Failed" Then
        Rows("51:51").EntireRow.Hidden = False
    End If

End Sub

To have the row hide/unhide update as you change the sheet, put it in a Worksheet_Change event:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Range("E50").Value = "Passed" Then
        Rows("51:51").EntireRow.Hidden = True
    ElseIf Range("E50").Value = "Failed" Then
        Rows("51:51").EntireRow.Hidden = False

    End If
End Sub
0

there was no typo. "rows(51)" is valid. but you don't need the "entirerow" modifier

rows(n).hidden=true    ; where n is an valid row number

to hide multiple rows

 range(rows(n1),rows(n2)).hidden=true ; will hide rows n1 though n2
Private Sub PG1()
    Range("$E$51").EntireRow.Hidden = (Range("$E$50").Value = "Passed")
End Sub
1
David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.