Home > Net >  Excel/VBA Show or hide rows based on specific cell values
Excel/VBA Show or hide rows based on specific cell values

Time:01-04

I am trying to find a way to find a way to show or hide rows 55:57 based on the value in Cell J52. Ideally, I would want this to happen in Real-Time Using VBA.

enter image description here

The value in J52 goes from 0 - 3.

I tried this code but it doesn't work as it throws an error stating "Sub or Function not defined":

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
StartRow = 55
EndRow = 57
Tar = C52
For i = Tar To Tar
If Cell(i).Value = "Individuals" Then
Cells(StartRow, EndRow).EntireRow.Hidden = True
Else
Cells(StartRow, EndRow).EntireRow.Hidden = False
End If
Next i
End Sub

Any help would be appreciated. Thanks.

CodePudding user response:

This code will only fire when you change the value in C52. It does what your code suggests, rather than what your question suggests.

(Target.Value = "Individuals") will return TRUE/FALSE based on the value of Target - Target being the cell you changed (C52).

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$C$52" Then
        Range("55:57").EntireRow.Hidden = (Target.Value = "Individuals")
    End If
End Sub

CodePudding user response:

This is slightly lazy coding but I think it achieves what you're after?

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Range("55:57").EntireRow.Hidden = (Range("C52") = "Individuals")
End Sub
  • Related