Test or check if sheet exists

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

    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)

提交回复
热议问题