excelvbashow-hide

How to unhide rows that are not together succinctly?


I'm a beginner in coding and specially with VBA. I have an Excel document on which several rows are hidden. I need to unhide these rows, three or four at a time succinctly, until they are all unhidden. I have a button made out of a shape.

For now, my code ressemble this :

Sub UnhideObjectives()
Static currentStage As Integer

Rows("34:37").EntireRow.Hidden = True
Rows("42:45").EntireRow.Hidden = True
Rows("50:53").EntireRow.Hidden = True

Select Case currentStage
Case 0
Rows("34:37").EntireRow.Hidden = False
currentStage = 1
Case 1
Rows("34:37").EntireRow.Hidden = False
Rows("42:45").EntireRow.Hidden = False
currentStage = 2
Case 2
Rows("34:37").EntireRow.Hidden = False
Rows("42:45").EntireRow.Hidden = False
Rows("50:53").EntireRow.Hidden = False
currentStage = 0

End Select
End Sub

But, I would like a code that does not have the currentStage function that get in cycle and optimally, it would need to show the rows that are next to the cell that got activated by the cursor.

Thank you.


Solution

  • As far as I understand:

    (note that you can omit the first line if there is no other instance that hides the rows 34 - 37)

    After that, you jump to the next stage, but if the last stage (2) is reached, you jump back to the first stage (0). You can do this by adding 1 to the current stage and use the modulo operator:

      currentStage = (currentStage + 1) Mod 3
    

    Advice: Always specify the worksheet you want to work with. So your code could look like:

    Sub UnhideObjectives()
        Static currentStage As Integer
        With ActiveSheet ' (Or, for example, With ThisWorkbook.Sheets(1)
            .Rows("34:37").EntireRow.Hidden = False
            .Rows("42:45").EntireRow.Hidden = (currentStage < 1)
            .Rows("50:53").EntireRow.Hidden = (currentStage < 2)
        End With
        currentStage = (currentStage + 1) Mod 3
    End Sub
    

    Update: I don't understand what exactly you want to archive, but I guess you should have a look to the Selection_Change event. Maybe something like this (needs to be in the worksheet module, not in a regular module).

    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
        Target.Offset(1, 0).Resize(3).EntireRow.Hidden = False
    End Sub
    

    Target is the selected cell.
    Offset(1, 0) is the cell below
    Resize(3) are the next 3 cells below
    EntireRow means the complete 3 rows below the selected cell