Test or check if sheet exists

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

    Some folk dislike this approach because of an "inappropriate" use of error handling, but I think it's considered acceptable in VBA... An alternative approach is to loop though all the sheets until you find a match.

    Function WorksheetExists(shtName As String, Optional wb As Workbook) As Boolean
        Dim sht As Worksheet
    
        If wb Is Nothing Then Set wb = ThisWorkbook
        On Error Resume Next
        Set sht = wb.Sheets(shtName)
        On Error GoTo 0
        WorksheetExists = Not sht Is Nothing
    End Function
    

提交回复
热议问题