VBA Condition "If the sheet exists" Then...

Apprenti -  
ccm81 Posted messages 11033 Status Member -
Hello,

In my macro, I need to check if the sheet "NAME" exists before continuing my procedure, but I don't know how to write this in VBA. Does anyone have an answer?

Thank you!

Configuration: Windows XP / Internet Explorer 6.0

5 answers

  1. Patrice33740 Posted messages 8400 Registration date   Status Member Last intervention   1 784
     
    Hello,

    It is not necessary to loop to check if the sheet exists,
    just do this:

    Function Sheet_Exists(ByVal Sheet_Name As String) As Boolean Dim Sheet As Excel.Worksheet On Error GoTo Sheet_Absent_Error Set Sheet = ActiveWorkbook.Worksheets(Sheet_Name) On Error GoTo 0 Sheet_Exists= True Exit Function Sheet_Absent_Error: Sheet_Exists= False End Function

    and to use it:

    If Sheet_Exists("Sheet1") Then
    or

    If Not Sheet_Exists("Sheet1") Then
    6
    1. Marc
       

      Hello, Patrice

      Thank you very much, Your Function To test

      if a sheet exists works perfectly

      It's exactly what I needed

      I tried to adapt it for direct use in the Macro without success

      but it's not very important, using a function is ultimately much

      more practical

      Thanks again

      Best regards

      0
    2. ccm81 Posted messages 11033 Status Member 2 434
       

      Hello everyone

      A bit simpler for sheet_exists

      Public Function SheetExists(sheetName As String) As Boolean
      On Error Resume Next
      SheetExists = Not (Sheets(sheetName) Is Nothing)
      End Function

      Best regards

      0