在Excel中以编程方式隐藏WorkSheets

时间:2013-11-27 01:33:14

标签: excel vba

当我关闭Excel时,我试图隐藏工作簿中的所有工作表。我使用的代码隐藏了所有工作表,直到它到达最后一个。然后它给了我一个运行时错误'1004'方法'''''''''''''''''''''''''''''''''''我以为我可能需要多张纸,所以我删除了大部分纸张而且没有任何变化,除了我有更少的纸张。这是我试图使用的代码。我把它放在“ThisWorkbook”中。

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

我正在使用ActiveWorkbook.Sheets("Welcome").Visible = True取消隐藏解释如何启用宏的欢迎表,然后保存它以便在打开时我只显示欢迎表。当它打开时,我使用此代码取消隐藏工作表并隐藏欢迎表。

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

希望在启用宏后会发生这种情况,否则无需取消隐藏其他工作表。

1 个答案:

答案 0 :(得分:1)

感谢rdhs的帮助。如果您发布答案,我会接受。这是我最后的代码更改。

Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim sh As Worksheet

Application.ScreenUpdating = False
'' If it is the Welcome sheet then make it visible, else hide it.
For Each sh In Sheets
    If StrComp(sh.Name, INTRO_SHEETNAME, vbTextCompare) = 0 Then
            sh.Visible = xlSheetVisible
    Else
        sh.Visible = xlSheetVeryHidden
    End If
Next sh
'' Call subroutine to save changes.
SaveState

End Sub

Private Sub Workbook_Open()
Dim sh As Worksheet

Application.ScreenUpdating = False
'' Make all the sheets visible.
For Each sh In Sheets
    sh.Visible = True
Next sh
'' Hide the welcome sheet.
ActiveWorkbook.Sheets("Welcome").Visible = xlSheetVeryHidden
Worksheets("Service").Protect UserInterfaceOnly:=True
Application.ScreenUpdating = True
Worksheets("Service").Activate

End Sub

在打开和关闭工作簿时调用“ThisWorkbook”中的代码。