Test or check if sheet exists

后端 未结 22 2540
深忆病人
深忆病人 2020-11-21 23:51
Dim wkbkdestination As Workbook
Dim destsheet As Worksheet

For Each ThisWorkSheet In wkbkorigin.Worksheets 
    \'this throws subscript out of range if there is not         


        
相关标签:
22条回答
  • 2020-11-22 00:08

    I did another thing: delete a sheet only if it's exists - not to get an error if it doesn't:

    Excel.DisplayAlerts = False 
    Dim WS
    For Each WS In Excel.Worksheets
        If WS.name = "Sheet2" Then
            Excel.sheets("Sheet2").Delete
            Exit For
        End If
    Next
    Excel.DisplayAlerts = True
    
    0 讨论(0)
  • 2020-11-22 00:09

    Short and clean:

    Function IsSheet(n$) As Boolean
        IsSheet = Not IsError(Evaluate(n & "!a1"))
    End Function
    
    0 讨论(0)
  • 2020-11-22 00:11

    I actually had a simple way to check if the sheet exists and then execute some instruction:

    In my case I wanted to delete the sheet and then recreated the same sheet with the same name but the code was interrupted if the program was not able to delete the sheet as it was already deleted

    Sub Foo ()
    
        Application.DisplayAlerts = False
    
        On Error GoTo instructions
        Sheets("NAME OF THE SHEET").Delete
    
        instructions:
    
        Sheets.Add After:=Sheets(Sheets.Count)
        ActiveSheet.Name = "NAME OF THE SHEET"
    
    End Sub
    
    0 讨论(0)
  • 2020-11-22 00:13

    As checking for members of a collection is a general problem, here is an abstracted version of Tim's answer:

    Function Contains(objCollection As Object, strName as String) As Boolean
        Dim o as Object
        On Error Resume Next
        set o = objCollection(strName)
        Contains = (Err.Number = 0)
        Err.Clear
     End Function
    

    This function can be used with any collection like object (Shapes, Range, Names, Workbooks, etc.).

    To check for the existence of a sheet, use If Contains(Sheets, "SheetName") ...

    0 讨论(0)
  • 2020-11-22 00:13

    Corrected: Without error-handling:

    Function CheckIfSheetExists(SheetName As String) As Boolean
          CheckIfSheetExists = False
          For Each WS In Worksheets
            If SheetName = WS.name Then
              CheckIfSheetExists = True
              Exit Function
            End If
          Next WS
    End Function
    
    0 讨论(0)
  • 2020-11-22 00:13

    Without any doubt that the above function can work, I just ended up with the following code which works pretty well:

    Sub Sheet_exist ()
    On Error Resume Next
    If Sheets("" & Range("Sheet_Name") & "") Is Nothing Then
        MsgBox "doesnt exist"
    Else
        MsgBox "exist"
    End if
    End sub
    

    Note: Sheets_Name is where I ask the user to input the name, so this might not be the same for you.

    0 讨论(0)
提交回复
热议问题