I have a pair of buttons (‘continue’ and ‘back’) which move a user forward and back worksheets.
The forward button seems to be able to move forward through visible sheets with no trouble, skipping hidden sheets fine.
The back button however, fails to do anything if there is a hidden sheet between the active sheet and the previous visible sheets.
I’m confused because the code for the two is practically identical:
Forward: (works fine)
Sub MoveNext() On Error Resume Next Sheets(ActiveSheet.Index + 1).Activate If Err.Number <> 0 Then Sheets(1).Activate End Sub
Back: (fails at hidden sheet)
Sub MoveBack() On Error Resume Next Sheets(ActiveSheet.Index - 1).Activate If Err.Number <> 0 Then Sheets(1).Activate End Sub
Each button is bound to the subs above as suitable.
Interesting! It looks like if you try to activate a hidden worksheet, it defaults to the next highest index. So that’s why it works going up, but not going down. I wrote a routine that checks whether there’s a lower visible sheet, and if so, moves to it:
Sub MoveBack() Dim PrevVisibleIndex As Long PrevVisibleIndex = ActiveSheet.Index With ThisWorkbook Do PrevVisibleIndex = Application.WorksheetFunction.Max(PrevVisibleIndex - 1, 1) Loop Until .Worksheets(PrevVisibleIndex).Visible = True Or PrevVisibleIndex = 1 .Worksheets(PrevVisibleIndex).Activate End With End Sub