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

时间:2011-07-27 01:19:07

标签: excel vba excel-2007

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

4 个答案:

答案 0 :(得分:13)

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

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

编辑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想要的”代码......

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

答案 1 :(得分:3)

这样的事情会让你开始:

On Error Resume Next

Dim wSheet as Worksheet
Set wSheet = Sheets(1) ' can also be a string, such as Sheets("Sheet1")

If wSheet Is Nothing Then
    MsgBox "Worksheet not found!"
    Set wSheet = Nothing ' make the worksheet point to nothing. 
    On Error GoTo 0 
Else 
    MsgBox "Worksheet found!"
    Set wSheet = Nothing ' set the found Worksheet object to nothing.  You can use the found wSheet for your purposes, though.  
End If

此代码基于http://www.ozgrid.com/VBA/IsWorkbookOpen.htm。查找DoesSheetExist()子。

希望这有帮助!

答案 2 :(得分:0)

我将此代码用于LotusScript,这是IBM Notes(以前称为Lotus Notes)使用的语言之一,如下所示。

Public Function ExcelSheetExists( _
    xlBook As Variant, _ ' Excel workbook object
    ByVal strSheetName As String _
    ) As Boolean

    On Error GoTo errHandler

    ForAll xlSheet In xlBook.Sheets
        If xlSheet.Name = strSheetName Then
            ExcelSheetExists = True
            Exit Forall
        End If
    End ForAll

    GoTo Done

errHandler:
    ' Call MyCustomErrorHandler()
    Resume Done
Done:

End Function

答案 3 :(得分:0)

On Error GoTo Line1
If Sheets("BOX2").Index > 0 Then
Else
Line1: MsgBox ("BOX2 is missing")
end if 

我是这样做的:)