以下是我正在尝试使用的代码。当单击显示/隐藏表单时,应该展开和折叠多个工作表。我有一个工作迭代,但完成后工作簿将超过200张,我希望将这些指定为我可以引用的集合,而不是指向应该专门展开或折叠的每个工作表。第二个for循环是我如何在我的其他迭代中设置代码并且它工作,想知道是否有办法使第一个for循环工作。干杯!
Private Sub Worksheet_Activate()
Dim sheet As Worksheet
Dim col1 As New Collection
Dim col2 As New Collection
col1.Add (BASE1) And (Cap1) And (A1) And (A2) And (CAP0) And (BASE0) And (Sheet13)
col2.Add (BASE0) And (CAP0) And (BASE1) And (Cap1) And (BASE2) And (Cap2) And (Sheet13)
Application.ScreenUpdating = False
If Sheet13.Name = "Show" Then
For Each sheet In ThisWorkbook.Sheets
If (sheet.Name <> col2) Then
sheet.Visible = xlSheetVisible
End If
Next sheet
Sheet13.Name = "Collapse"
Sheet3.Activate
Else
For Each sheet In ThisWorkbook.Sheets
If (sheet.Name <> Sheet1.Name And sheet.Name <> Sheet2.Name And sheet.Name <> Sheet3.Name And sheet.Name <> Sheet13.Name And sheet.Name <> Sheet7.Name) Then
sheet.Visible = xlSheetVeryHidden
End If
Next sheet
Sheet13.Name = "Show"
Sheet3.Activate
End If
Application.ScreenUpdating = True
End Sub
希望这有助于澄清我的问题。以下代码是上述代码的当前工作版本,不使用集合。如您所见,具体引用了要展开和折叠的工作表。我想做的是如果sheet.Name&lt;&gt; (集合1中的任何表格)然后
Private Sub Worksheet_Activate()
Dim sheet As Worksheet
Application.ScreenUpdating = False
If Sheet8.Name = "702 BASE - EXPAND" Then
For Each sheet In ThisWorkbook.Sheets
If (sheet.Name <> Sheet4.Name And sheet.Name <> Sheet5.Name And sheet.Name <> Sheet6.Name And sheet.Name <> Sheet14.Name And sheet.Name <> Sheet15.Name And sheet.Name <> Sheet16.Name And sheet.Name <> Sheet17.Name And sheet.Name <> Sheet18.Name And sheet.Name <> Sheet19.Name And sheet.Name <> Sheet20.Name And sheet.Name <> Sheet21.Name And sheet.Name <> Sheet22.Name And sheet.Name <> Sheet23.Name And sheet.Name <> Sheet24.Name And sheet.Name <> Sheet25.Name And sheet.Name <> Sheet26.Name) Then
sheet.Visible = xlSheetVisible
End If
Next sheet
Sheet8.Name = "702 BASE - COLLAPSE"
Sheet8.Activate
Else
For Each sheet In ThisWorkbook.Sheets
If (sheet.Name <> Sheet4.Name And sheet.Name <> Sheet8.Name And sheet.Name <> Sheet1.Name And sheet.Name <> Sheet2.Name And sheet.Name <> Sheet3.Name And sheet.Name <> Sheet7.Name) Then
sheet.Visible = xlSheetVeryHidden
End If
Next sheet
Sheet8.Name = "702 BASE - EXPAND"
Sheet1.Activate
End If
Application.ScreenUpdating = True
End Sub
答案 0 :(得分:1)
这是您的代码的简化版本,用于说明一种可能的方法:
Private Sub Worksheet_Activate()
Dim sheet As Worksheet
Dim arr1, arr2
arr1 = Array(BASE1, Cap1, A1, A2, CAP0, BASE0, Sheet13)
Application.ScreenUpdating = False
If Sheet13.Name = "Show" Then '<< can use "Me.Name" if code is in Sheet13 module...
For Each sheet In ThisWorkbook.Sheets
If Not InArray(sheet, arr1) Then sheet.Visible = xlSheetVisible
Next sheet
Sheet13.Name = "Collapse"
Sheet3.Activate
End If
Application.ScreenUpdating = True
End Sub
一个实用程序函数,用于检查工作表是否在提供的数组中。应该进入常规代码模块。
'is a sheet in the provided array?
Function InArray(sht As Worksheet, arr)
Dim s, rv As Boolean
For Each s In arr
If s.Name = sht.Name Then
rv = True
Exit For
End If
Next s
InArray = rv
End Function