如何检查Excel-VBA中是否存在某些图纸?

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

尽pipe(不幸)这种方法不可用,但我们可以创build自己的函数来检查这个..

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

编辑1:添加也删除语句…

Sub test() If CheckSheet(Sheets(3).Name) then Application.DisplayAlerts = False Sheets(Sheets(3).Name).Delete Application.DisplayAlerts = True End If End Sub 

我要去的解决scheme…

 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 

像这样的东西会让你开始:

 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()子。

希望这可以帮助!

我调整了这个代码以用于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 
 On Error GoTo Line1 If Sheets("BOX2").Index > 0 Then Else Line1: MsgBox ("BOX2 is missing") end if 

我这样做:)