隐藏或取消隐藏所有Excel工作表,而不循环 [英] Hide or Unhide all Excel Sheets Without Looping
本文介绍了隐藏或取消隐藏所有Excel工作表,而不循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含179个工作表的工作簿。我想隐藏所有工作表(根据Excel的规则保留一个未隐藏的工作表),或取消隐藏所有工作表。
目前我的代码如下所示(根据我们是否隐藏/取消隐藏工作表进行适当的修改):
For Each Sht in Wb.Worksheets
Sht.Visible = xlSheetVisible
Next Sht
对于179个工作表,这需要4-5秒才能运行,我希望它运行得更快。
我知道,如果我进入工作簿,手动选择所有工作表(只有一个工作表除外),然后右击并选择"Hide"
,所有工作表都会立即隐藏。我无法在VBA代码中重现此内容。
如上所述,我需要以某种方式快速隐藏工作簿中的所有(一个除外)工作表,并取消隐藏工作簿中的所有工作表而不循环。如有任何帮助,我们不胜感激!
推荐答案
如前所述,您只能隐藏多张表而不使用循环,如下所示:
Worksheets(Array(1,2,3,4,5,6,7,8,9,10,11,...,200)).Visible = True
但取消隐藏多张工作表需要循环
但是有一种速度更快的方法,那就是使用自定义视图(在视图选项卡中)
下面的代码生成2个视图1。"ShowAllWs",和2."隐藏所有工作"
性能智慧:
For 201 Worksheets
Loop HideAll - Time: 0.039 sec (initial setup - sets array, except one Ws in one operation)
Loop ShowAll - Time: 0.648 sec (initial setup - unhides all using a loop)
View ShowAll - Time: 0.023 sec (consecutive runs - no loop)
View HideAll - Time: 0.023 sec (consecutive runs - no loop)
Option Explicit
Public Sub SetWsVisibility(Optional ByVal vis As Boolean = False, _
Optional ByVal visibleWs As Long = 0)
Static vSet As Boolean, hSet As Boolean, wsCount As Long, lastV As Long, i As Long
With ThisWorkbook
wsCount = .Worksheets.Count - 1
'if visibleWs is 0 last ws is visible, or use any other valid sheet index
visibleWs = IIf(visibleWs < 1 Or visibleWs > wsCount, wsCount + 1, visibleWs)
If wsCount <> .Worksheets.Count - 1 Or visibleWs <> lastV Then
vSet = False
hSet = False
Else
If vSet And vis Then .CustomViews("ShowAllWs").Show: Exit Sub
If hSet And Not vis Then .CustomViews("HideAllWs").Show: Exit Sub
End If
Application.ScreenUpdating = False
If vis Then
For i = 1 To wsCount + 1
With .Worksheets(i)
If Not .Visible Then .Visible = vis
End With
Next
.Worksheets(1).Activate
.CustomViews.Add ViewName:="ShowAllWs" 'Save View (one-time operation)
vSet = True
Else
If visibleWs <> lastV Then
For i = 1 To wsCount + 1
With .Worksheets(i)
If Not .Visible Then .Visible = 1
End With
Next
End If
Dim arr() As Variant, j As Long
ReDim arr(1 To wsCount)
j = 1
For i = 1 To wsCount + 1
If i <> visibleWs Then arr(j) = i Else j = j - 1
j = j + 1
Next
.Worksheets(arr).Visible = vis
.CustomViews.Add ViewName:="HideAllWs" 'Save View (one-time operation)
hSet = True
lastV = visibleWs
End If
Application.ScreenUpdating = True
End With
End Sub
若要调用它,请使用以下命令:
Public Sub UpdateWsVisibility()
SetWsVisibility 0, 5 'or 0 to hide them (or True / False respectively)
End Sub
这篇关于隐藏或取消隐藏所有Excel工作表,而不循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文