【发布时间】:2011-10-13 21:13:57
【问题描述】:
有谁知道如何使用 Excel VBA 检查 Excel 文档中是否存在某些工作表?
【问题讨论】:
标签: excel vba excel-2007
有谁知道如何使用 Excel VBA 检查 Excel 文档中是否存在某些工作表?
【问题讨论】:
标签: excel vba excel-2007
虽然(不幸的是)这种方法不可用,但我们可以创建自己的函数来检查这个..
希望下面的代码能满足您的需求。
Edit1:还添加了删除语句...
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 Programmingwannabe”代码...
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
【讨论】:
Sheets(1).name 可以解决问题。请注意,您可能需要主动定义要使用的工作簿,因为“工作表”引用隐式指向活动工作簿(有时这不是预期的)。
这样的事情会让你开始:
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() 子。
希望这会有所帮助!
【讨论】:
我修改了此代码以在 LotusScript 中使用,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
【讨论】:
On Error GoTo Line1
If Sheets("BOX2").Index > 0 Then
Else
Line1: MsgBox ("BOX2 is missing")
end if
我是这样做的:)
【讨论】: