Test or check if sheet exists

后端 未结 22 2568
深忆病人
深忆病人 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:14

    You don't need error handling in order to accomplish this. All you have to do is iterate over all of the Worksheets and check if the specified name exists:

    For i = 1 To Worksheets.Count
        If Worksheets(i).Name = "MySheet" Then
            exists = True
        End If
    Next i
    
    If Not exists Then
        Worksheets.Add.Name = "MySheet"
    End If
    
    0 讨论(0)
  • 2020-11-22 00:14
        For Each Sheet In Worksheets
        If UCase(Sheet.Name) = "TEMP" Then
        'Your Code when the match is True
            Application.DisplayAlerts = False
            Sheet.Delete
            Application.DisplayAlerts = True
        '-----------------------------------
        End If
    Next Sheet
    
    0 讨论(0)
  • 2020-11-22 00:16

    In case anyone wants to avoid VBA and test if a worksheet exists purely within a cell formula, it is possible using the ISREF and INDIRECT functions:

    =ISREF(INDIRECT("SheetName!A1"))

    This will return TRUE if the workbook contains a sheet called SheetName and FALSE otherwise.

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

    Change "Data" to whatever sheet name you're testing for...

    On Error Resume Next 
    
    Set DataSheet = Sheets("Data")
    
    If DataSheet Is Nothing Then
    
         Sheets.Add(after:=ActiveSheet).Name = "Data"
         ''or whatever alternate code you want to execute''
    End If
    
    On Error GoTo 0
    
    0 讨论(0)
  • I wrote this one:

    Function sheetExist(sSheet As String) As Boolean
    On Error Resume Next
    sheetExist = (ActiveWorkbook.Sheets(sSheet).Index > 0)
    End Function
    
    0 讨论(0)
  • 2020-11-22 00:21

    I came up with an easy way to do it, but I didn't create a new sub for it. Instead, I just "ran a check" within the sub I was working on. Assuming the sheet name we're looking for is "Sheet_Exist" and we just want to activate it if found:

    Dim SheetCounter As Integer
    
    SheetCounter = 1
    
    Do Until Sheets(SheetCounter).Name = "Sheet_Exist" Or SheetCounter = Sheets.Count + 1
     SheetCounter = SheetCounter +1
    Loop
    If SheetCounter < Sheets.Count + 1 Then
     Sheets("Sheet_Exist").Activate
    Else
     MsgBox("Worksheet ""Sheet_Exist"" was NOT found")
    End If
    

    I also added a pop-up for when the sheet doesn't exist.

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