Test or check if sheet exists

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

    Put the test in a function and you will be able to reuse it and you have better code readability.

    Do NOT use the "On Error Resume Next" since it may conflict with other part of your code.

    Sub DoesTheSheetExists()
        If SheetExist("SheetName") Then
            Debug.Print "The Sheet Exists"
        Else
            Debug.Print "The Sheet Does NOT Exists"
        End If
    End Sub
    
    Function SheetExist(strSheetName As String) As Boolean
        Dim i As Integer
    
        For i = 1 To Worksheets.Count
            If Worksheets(i).Name = strSheetName Then
                SheetExist = True
                Exit Function
            End If
        Next i
    End Function
    

提交回复
热议问题