检查表是否存在,如果不存在-VBA

时间:2019-02-22 09:04:14

标签: excel vba

我已经测试了许多代码,这些代码检查表是否存在(基于名称),如果不存在则创建一个。然后一些循环所有工作表,有些则引用工作表,如果创建错误,则表示该工作表不存在。哪种方法最合适-正统-更快地完成此任务?

当前我正在使用:

Option Explicit

Sub test()     
    Dim ws As Worksheet
    Dim SheetName As String
    Dim SheetExists As Boolean

    SheetName = "Test"
    SheetExists = False

    With ThisWorkbook
        'Check if the Sheet exists
        For Each ws In .Worksheets
            If ws.Name = SheetName Then
                SheetExists = True
                Exit For
            End If   
        Next

        If SheetExists = False Then
            'If the sheet dont exists, create
            .Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = SheetName
        End If
    End With 
End Sub

2 个答案:

答案 0 :(得分:4)

这就是我用的。无需循环。直接尝试分配给一个对象。如果成功,则意味着该工作表存在:)

Function DoesSheetExists(sh As String) As Boolean
    Dim ws As Worksheet

    On Error Resume Next
    Set ws = ThisWorkbook.Sheets(sh)
    On Error GoTo 0

    If Not ws Is Nothing Then DoesSheetExists = True
End Function

用法

Sub Sample()
    Dim s As String: s = "Sheet1"

    If DoesSheetExists(s) Then
        '
        '~~> Do what you want
        '
    Else
        MsgBox "Sheet " & s & " does not exist"
    End If
End Sub

答案 1 :(得分:3)

Sub solution1()    
    If Not sheet_exists("sheetnotfound") Then
        ThisWorkbook.Sheets.Add( _
                    After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)).Name = _
                    "sheetnotfound"
    End If    
End Sub


Function sheet_exists(strSheetName As String) As Boolean        
    Dim w As Excel.Worksheet
    On Error GoTo eHandle
    Set w = ThisWorkbook.Worksheets(strSheetName)
    sheet_exists = True

    Exit Function 
eHandle:
    sheet_exists = False
End Function
相关问题