如何检查Excel-VBA中是否存在某些工作表?

Viv*_*ian 10 excel vba excel-2007

有谁知道如何使用Excel VBA检查Excel文档中是否存在某些工作表?

Tia*_*oso 13

虽然(不幸的是)这样的方法不可用,但我们可以创建自己的函数来检查这个.

希望下面的代码符合您的需求.

Edit1:还添加了删除语句......

Sub test()

    If CheckSheet(Sheets(3).Name) then

        Application.DisplayAlerts = False
        Sheets(Sheets(3).Name).Delete
        Application.DisplayAlerts = True

    End If

End Sub
Run Code Online (Sandbox Code Playgroud)

我想要的解决方案......

Function CheckSheet(ByVal sSheetName As String) As Boolean

    Dim oSheet As Excel.Worksheet
    Dim bReturn As Boolean

    For Each oSheet In ActiveWorkbook.Sheets

        If oSheet.Name = sSheetName Then

            bReturn = True
            Exit For

        End If

    Next oSheet

    CheckSheet = bReturn

End Function
Run Code Online (Sandbox Code Playgroud)

或者,如果您不介意使用主动引发错误的代码(通常的编码最佳实践不推荐),您可以使用下面的" Spartan Programming wannabe"代码...

Function CheckSheet(ByVal sSheetName As String) As Boolean

    Dim oSheet As Excel.Worksheet
    Dim bReturn As Boolean

    For Each oSheet In ActiveWorkbook.Sheets

        If oSheet.Name = sSheetName Then

            bReturn = True
            Exit For

        End If

    Next oSheet

    CheckSheet = bReturn

End Function


Function CheckSheet(ByVal sSheetName As String) As Boolean

    On Error Resume Next
    Dim oSheet As Excel.Worksheet

    Set oSheet = ActiveWorkbook.Sheets(sSheetName)
    CheckSheet = IIf(oSheet Is Nothing, False, True)

End Function
Run Code Online (Sandbox Code Playgroud)