VBA code to hide or unhide rows based on a cell value

195,380

Solution 1

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

Solution 2

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
Share:
195,380

Related videos on Youtube

I AM L
Author by

I AM L

Updated on September 18, 2022

Comments

  • I AM L
    I AM L almost 2 years

    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.

  • DavidPostill
    DavidPostill over 9 years
    Welcome to Super User! Could you please edit your answer to give an explanation of why this code answers the question?