问题
我正在运行一个宏,该宏会根据用户输入创建多个新工作表;至少一个“主”工作表和几个“子”工作表。这些文件的格式类似于“ Group 1 Master”,“ Group 1 Sub 1”,“ Group 2 Sub 2”,“ Group 2 Sub 3” .......“ Group n Master”,“ Group n Sub 1“ ......
我想找到一种隐藏子表的方法,直到选择/激活其子表为止,这时它们应该变得可见,然后当未选择母表时,应再次隐藏它们。 / p>
方法
我发现sources表示如何通过在给定的工作表中插入类似以下子项的内容来手动实现此目的,但是我的工作表是由宏生成的,所以我不想手动进行操作通过并将其添加到所有这些。
Private Sub Worksheet_Activate()
For Each SubSheet in SubSheets
SubSheet.Visible = False
Next SubSheet
End Sub
问题
如何隐藏所有子工作表,而不选择它们的主工作表?
谢谢
答案 0 :(得分:1)
想象一下这是所有可见的表格的样子:
这就是隐藏所有子工作表的样子:
这是它与自动隐藏/显示活动主表的子表一起工作的方式:
我使用了以下代码:
Option Explicit
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
'find master left of selected sheet
Dim ActiveMaster As Object
Dim iSht As Long
For iSht = Sh.Index To 1 Step -1 'loop backwards until a master is found
If InStr(1, ThisWorkbook.Sheets(iSht).Name, "Master") > 0 Then
Set ActiveMaster = ThisWorkbook.Sheets(iSht)
Exit For
End If
Next iSht
If ActiveMaster Is Nothing Then
'no master sheet left of current sheet found
MsgBox "No 'Master' sheet found.", vbCritical
Exit Sub
End If
'find last sub sheet
Dim LastSub As Object
For iSht = ActiveMaster.Index + 1 To ThisWorkbook.Sheets.Count
If InStr(1, ThisWorkbook.Sheets(iSht).Name, "Master") > 0 Then
Set LastSub = ThisWorkbook.Sheets(iSht - 1)
Exit For
End If
Next iSht
'if no last sub sheet was found it is the very last sheet
If LastSub Is Nothing Then
Set LastSub = ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
End If
'hide all SUB-sheets left of master sheet and right of LastSub sheet
If ActiveMaster.Index > 1 Then
For iSht = 1 To ThisWorkbook.Sheets.Count
If iSht < ActiveMaster.Index Or iSht > LastSub.Index Then
If InStr(1, ThisWorkbook.Sheets(iSht).Name, "Master") = 0 Then
ThisWorkbook.Sheets(iSht).Visible = xlSheetHidden
End If
Else
ThisWorkbook.Sheets(iSht).Visible = xlSheetVisible
End If
Next iSht
End If
End Sub
Public Sub ShowAllSheets()
Dim iSht As Long
For iSht = 1 To ThisWorkbook.Sheets.Count
ThisWorkbook.Sheets(iSht).Visible = xlSheetVisible
Next iSht
End Sub
Public Sub HideAllSubSheets()
Dim iSht As Long
For iSht = 1 To ThisWorkbook.Sheets.Count
If InStr(1, ThisWorkbook.Sheets(iSht).Name, "Master") = 0 Then
ThisWorkbook.Sheets(iSht).Visible = xlSheetHidden
End If
Next iSht
End Sub