Excel – Hide multiple rows in excel VBA

microsoft excelvba

I am trying to hide all rows containing the value "xx" in column A and not hide the rows containing "a" in column A. The range is from A8:A556. This macro needs to be triggered by a change in cell C4.

Any idea why it is not working? Here's the current attempt:

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Address(True, True) = "$C$4" Then

    If Range("A8:A555").Value = "xx" Then
        Rows("8:555").EntireRow.Hidden = True
    ElseIf Range("A8:A555").Value = "a" Then
        Rows("8:555").EntireRow.Hidden = False

     End If
   End If

End Sub

Thanks!

EDIT:

Hey Fixer1234, Here is the detail:

  • "xx" and "a" may not exist together if the macro works correctly.
  • Only "xx" rows must be hidden
  • "xx" values are not in combination with values that cannot be hidden.
  • "a" values are not in combination with values that must be hidden.
  • there are other rows that do not contain "xx or "a" that don't need to be hidden (should I add an "a" to these columns or completely remove the IfElse?).
  • "xx" row contain other formulas, a blank result from the formula means the row must be hidden.
  • "a" rows have the same formula but it produces a result and must not be hidden.

Run-time error '13': type mismatch
and then the debug goes to the first
If Range("A8:A555").Value = "xx" Then

Best Answer

You can't test all the values in a range using Range("A8:A555").Value = "xx". It will throw a Type Mismatch error.

You need to loop through each cell in the range and test individually if its Value equals "xx".

To make the code run faster, don't hide rows as you detect them but build up a Range of Ranges to be hidden then hide them all at once.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim cel As Range
Dim RangeToHide As Range

    'Test if Target is C4
    If Not Intersect(Target, [C4]) Is Nothing Then
        'Loop through each cell in range and test if it's "xx"
        For Each cel In Range("A8:A555")
            If cel = "xx" Then
                If RangeToHide Is Nothing Then
                    'Initialise RangeToHide because Union requires at least 2 ranges
                    Set RangeToHide = cel
                Else
                    'Add cel to RangeToHide
                    Set RangeToHide = Union(RangeToHide, cel)
                End If
            End If
        Next
        RangeToHide.EntireRow.Hidden = True
    End If
End Sub
Related Question