Test or check if sheet exists

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

    I know it is an old post, but here is another simple solution that is fast.

    Public Function worksheetExists(ByVal wb As Workbook, ByVal sheetNameStr As String) As Boolean
    
    On Error Resume Next
    worksheetExists = (wb.Worksheets(sheetNameStr).Name <> "")
    Err.Clear: On Error GoTo 0
    
    End Function
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 00:31

    Compact wsExists function (without reliance on Error Handling!)

    Here's a short & simple function that doesn't rely on error handling to determine whether a worksheet exists (and is properly declared to work in any situation!)

    Function wsExists(wsName As String) As Boolean
        Dim ws: For Each ws In Sheets
        wsExists = (wsName = ws.Name): If wsExists Then Exit Function
        Next ws
    End Function
    

    Example Usage:

    The following example adds a new worksheet named myNewSheet, if it doesn't already exist:

    If Not wsExists("myNewSheet") Then Sheets.Add.Name = "myNewSheet"
    

    More Information:

    • MSDN : For Each…Next Statement (VBA)
    • MSDN : Exit Statement (VBA)
    • MSDN : Comparison Operators (VBA)
    0 讨论(0)
  • 2020-11-22 00:32

    Why not just use a small loop to determine whether the named worksheet exists? Say if you were looking for a Worksheet named "Sheet1" in the currently opened workbook.

    Dim wb as Workbook
    Dim ws as Worksheet
    
    Set wb = ActiveWorkbook
    
    For Each ws in wb.Worksheets
    
        if ws.Name = "Sheet1" then
            'Do something here
        End if
    
    Next
    
    0 讨论(0)
提交回复
热议问题