title: Hiding WorkSheets Programmatically in Excel
body: <p>I am trying to hide all of the sheets in a Workbook when I close Excel. The code I am using hides all of the sheets until it gets to the last one. Then it gives me a Run-time error '1004' Method'Visible'of'Object'_Worksheet failed. I thought I may have had to many sheets so I deleted most of them and nothing changes except I had fewer sheets. This is the code I am trying to use. I placed it in "ThisWorkbook".</p>
  
  <pre><code>Private Sub Workbook_BeforeClose(Cancel As Boolean)
  Dim sh As Worksheet
  
  
  For Each sh In Sheets
      If StrComp(sh.Name, C_INTRO_SHEETNAME, vbTextCompare) = 0 Then
          sh.Visible = xlSheetVisible
      Else
          sh.Visible = xlSheetVeryHidden
      End If
  Next sh
  
  ActiveWorkbook.Sheets("Welcome").Visible = True
  SaveState
  
  End Sub
  </code></pre>
  
  <p>I am using <code>ActiveWorkbook.Sheets("Welcome").Visible = True</code> to unhide the welcome sheet that explains how to enable macros then I save it so when it opens I only have the welcome sheet visible. When it opens I use this code to unhide the sheets and hide the welcome sheet.</p>
  
  <pre><code>Private Sub Workbook_Open()
  Dim sh As Worksheet
  
  For Each sh In Sheets
      sh.Visible = True
  Next sh
  
  ActiveWorkbook.Sheets("Welcome").Visible = xlSheetVeryHidden
  Worksheets("Service").Protect UserInterfaceOnly:=True
  Worksheets("Service").Activate
  
  End Sub
  </code></pre>
  
  <p>Hopefully this will happen after they enable macros, otherwise there is no need to unhide the other sheets.</p>