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

18 浏览
0 Comments

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

这个问题已经在这里得到了回答

测试或检查表格是否存在

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

admin 更改状态以发布 2023年5月23日
0
0 Comments

以下内容可以帮助您入门:

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

希望这能帮到您!

0
0 Comments

虽然(不幸地)没有这种方法可用,但我们可以创建自己的函数来检查这个问题。

希望下面的代码能满足您的需要。

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

或者,如果你不介意使用会主动引发错误的代码(这不是常见的编码最佳实践建议),你可以使用下面这个“ 斯巴达编程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

0