我在Excel 2013中有一个UserForm,可以在操作之前清除用户的Excel页面。公共模块具有以下VBA代码:
Sub ShowForm()
With ActiveWorkbook
.Worksheets("Sheet1").Activate
.Worksheets("Sheet2").Visible = False 'Hide didn't work
.Worksheets("Sheet3").Visible = False 'Hide didn't work
End With
UserForm1.Show
End Sub
如何隐藏工作表2和3并激活或使工作表1可见?代码应该模仿右键单击选项卡并选择"隐藏"。上面的代码抛出Run-time error '9': Subscript out of range
。
答案 0 :(得分:0)
在隐藏除活动工作表之外的所有内容之后,您似乎已经过了。试试这段代码 - 它不依赖于工作表名称。
Sub Test()
SheetVisibility 'Hide all except active sheet.
MsgBox "All except `" & ActiveSheet.Name & "` hidden."
SheetVisibility True 'Unhide all sheets.
End Sub
Sub SheetVisibility(Optional ShowAll As Boolean = False)
Dim wrkSht As Worksheet
For Each wrkSht In ThisWorkbook.Worksheets
If wrkSht.Name <> ActiveSheet.Name Then
wrkSht.Visible = IIf(ShowAll, xlSheetVisible, xlSheetHidden)
End If
Next wrkSht
End Sub