【问题标题】:Check if sheet exists, if not create -VBA [duplicate]检查工作表是否存在,如果不存在则创建-VBA [重复]
【发布时间】:2019-07-16 08:01:24
【问题描述】:

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

目前我正在使用:

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

【问题讨论】:

标签: excel vba


【解决方案1】:

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

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

【讨论】:

  • 一个漂亮简单的解决方案,我一直在寻找几个小时。需要根据文件夹中的文件检查工作表名称。我是使用函数的新手,但在此之后,我将寻求在未来的解决方案中使用它们。
【解决方案2】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 2014-07-23
    • 2011-05-12
    • 1970-01-01
    相关资源
    最近更新 更多