Go to First Sheet Not Hidden

Viewed 654

Working on a macro that will go to the first sheet. I was using:

Sub GoToFirstSheet()

    On Error Resume Next
    Sheets(1).Select

End Sub

However, if sheet 1 is hidden, this wont work. How can I incorporate a way to go to the first sheet that isn't hidden?

2 Answers

Something like this?

Option Explicit

Sub GoToFirstSheet()
    Dim i As Long

    For i = 1 To ThisWorkbook.Sheets.Count
        On Error Resume Next
        Sheets(i).Activate
        If Err.Number = 0 Then Exit For
    Next i
End Sub

This should do it:

Option Explicit
Sub GoToFirstSheet()

    Dim ws As Worksheet 'declare a worksheet variable
    'loop through all the worksheets in the workbook
    For Each ws In ThisWorkbook.Worksheets
        'If the sheet is not hidden
        If ws.Visible = xlSheetVisible Then
            ws.Select 'select it
            Exit For 'exit the loop
        End If
    Next ws

End Sub
Related