激活工作表1,否则激活另一个工作表

时间:2018-06-19 14:49:47

标签: excel vba excel-vba

您好,我尝试通过添加if语句来修改以下两行代码,但是没有用。有人知道为什么吗?

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

以下内容有什么问题?谢谢

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

1 个答案:

答案 0 :(得分:2)

考虑到您从这里取SheetExists-Test or check if sheet exists,这是可行的:

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

或者,如果您想看到同事发疯,请这样写:

Sub ActivateTab2OrTab1()

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

End Sub