Home » excel » excel – Activate sheet 1 otherwise another sheet

excel – Activate sheet 1 otherwise another sheet

Posted by: admin May 14, 2020 Leave a comment

Questions:

Hi I tried to modify the following two lines of code by adding an if statement, but it didn’t work. Does anyone know why?

Workbooks(wkbk_Record).Activate
Workbooks(wkbk_Record).Sheets("Tab1").Select

What’s wrong with the following? Thank you

If SheetExists("Tab1", Workbooks(wkbk_Record)) Then    
    Workbooks(wkbk_Record).Activate
    Workbooks(wkbk_Record).Sheets("Tab1").Select    
Else    
    Workbooks(wkbk_Record).Activate
    Workbooks(wkbk_Record).Sheets("Tab2").Select
How to&Answers:

Considering that you take the SheetExists from here – Test or check if sheet exists this is something that works:

Sub TestMe()

    If SheetExists("Tab1") Then
        Sheets("Tab1").Select
    ElseIf SheetExists("Tab2") Then
        Sheets("Tab2").Select
    Else
        MsgBox "No Sheet"
    End If

End Sub

 Function SheetExists(shtName As String, Optional wb As Workbook) As Boolean

     Dim sht As Worksheet

     If wb Is Nothing Then Set wb = ThisWorkbook
     On Error Resume Next
     Set sht = wb.Sheets(shtName)
     On Error GoTo 0
     SheetExists = Not sht Is Nothing

 End Function

Or if you wanna see your colleagues get crazy, write it like this:

Sub ActivateTab2OrTab1()

    On Error Resume Next
    Sheets("Tab2").Select
    Sheets("Tab1").Select

End Sub