Home » excel » excel vba – What is a Compact way to Refer to a Set of Non-Contiguous Rows?

excel vba – What is a Compact way to Refer to a Set of Non-Contiguous Rows?

Posted by: admin May 14, 2020 Leave a comment

Questions:

The below code seems inelegant and wasteful. Is there a more compact notation for referencing all those rows?

Sub HideEBRedData()
'un/hide EIRP Budget rows with redundant path data
Application.ScreenUpdating = False

Set EIRPBudget = Sheets("EIRP Budget")

With EIRPBudget
    .Rows(29).Hidden = Not .Rows(29).Hidden
    .Rows(30).Hidden = Not .Rows(30).Hidden
    .Rows(50).Hidden = Not .Rows(50).Hidden
    .Rows(51).Hidden = Not .Rows(51).Hidden
    .Rows(54).Hidden = Not .Rows(54).Hidden
    .Rows(55).Hidden = Not .Rows(55).Hidden
    .Rows(65).Hidden = Not .Rows(65).Hidden
    .Rows(66).Hidden = Not .Rows(66).Hidden
End With

Application.ScreenUpdating = True
End Sub

Simoco provided the answer I was looking for. Here it is:

Sub HideEBRedData()
'un/hide EIRP Budget rows with redundant path data
Application.ScreenUpdating = False

Dim r As Variant

Set EIRPBudget = Sheets("EIRP Budget")

For Each r In Array(29, 30, 50, 51, 54, 55, 65, 66)
    EIRPBudget.Rows(r).Hidden = Not EIRPBudget.Rows(r).Hidden
Next

Application.ScreenUpdating = True
End Sub
How to&Answers:

As follow up from comments, this code is what OP looking for:

Sub HideEBRedData()
    Dim r As Variant

    Application.ScreenUpdating = False

    Set EIRPBudget = Sheets("EIRP Budget")
    For Each r In Array(29, 30, 50, 51, 54, 55, 65, 66)
        EIRPBudget.Rows(r).Hidden = Not EIRPBudget.Rows(r).Hidden
    Next

    Application.ScreenUpdating = True
End Sub

Answer:

Consider:

Sub FlipHidden()
    Dim r As Range
    Set r = Range("A29,A30,A50,A51,A54,A55,A65,A66")
    r.EntireRow.Hidden = Not r.EntireRow.Hidden
End Sub

EDIT#1:

This macro will work if all rows are visible when the macro is run.