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

标签 excel vba excel-2007

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

最佳答案

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

希望下面的代码适合您的需求。

编辑1:还添加了删除语句...

Sub test()

    If CheckSheet(Sheets(3).Name) then

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

    End If

End Sub

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

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

或者,如果您不介意使用主动引发错误的代码(常见编码最佳实践不建议这样做),您可以使用此“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

关于excel - 如何检查Excel-VBA中某些工作表是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6838437/

相关文章:

excel - 无法将类型 'Microsoft.Office.Interop.Excel.ApplicationClass' 的 COM 对象转换为接口(interface)类型 'Microsoft.Office.Interop.Excel._Application'

excel - 为什么我会遇到这个 If 语句问题?

ms-access - 在执行报表打开事件之前 Access 报表运行查询

Excel图表动态范围选择

vba - 通过函数禁用按钮?

excel - 查找大于或等于某个值的所有值

python - 当某些单元格有多行时如何读取excel文件

excel - 索引/匹配 - 如果第一个值为空白,则查找第二个值

c++ - C++ 中的 CDBException(错误)处理(VS2010、MFC、Excel/ODBC)

vba - 在除命名工作表之外的所有工作表上运行删除重复代码