当前,我正在使用此VBA代码隐藏电子表格中的所有工作表:
Sub HideSheets()
Sheet1.Visible = False
Sheet2.Visible = False
Sheet3.Visible = False
Sheet4.Visible = True
End Sub
此代码运行完美。
但是,由于我的原始文件中只有4张纸,因此我希望有一个带有循环的解决方案。因此,我尝试使用以下公式:
Sub LoopHideSheets()
Dim b As Worksheet
For Each b In Worksheets
b.Select
ActiveWindow.Visible = False
Next b
End Sub
运行此代码后,我的Excel文件崩溃。我猜这是因为至少一个文件需要保持可见。您知道我必须更改循环代码以便隐藏所有工作表而不是Sheet4
吗?
答案 0 :(得分:1)
这将隐藏所有未命名为“ Sheet4”的工作表-但请注意,您需要确保Sheet4存在,否则会出现错误。
Sub LoopHideSheets()
Dim b As Worksheet
For Each b In Worksheets
If b.Name <> "Sheet4" Then b.Visible = False
Next b
End Sub
您可能希望隐藏除当前活动的页面以外的所有工作表。
If b.Name <> ActiveSheet.Name Then b.Visible = False
但是,您可能需要根据其他答案隐藏除1(嘿,我不知道为什么)之外的所有内容。要正确执行此操作,您需要计算可见的工作表,仅处理这些工作表:
Sub LoopHideSheets()
Dim b As Worksheet, shtcnt As Long
'Count up all visible sheets
For Each b In Worksheets
If b.Visible = True Then shtcnt = shtcnt + 1
Next b
'Hide each visible sheet until only 1 is left
For Each b In Worksheets
If b.Visible = True And shtcnt > 1 Then
shtcnt = shtcnt - 1
b.Visible = False
End If
Next b
End Sub
答案 1 :(得分:1)
Sub LoopHideSheets()
Dim b As Worksheet
For Each b In Worksheets
If b.Name <> "DontHide" Then 'whatever the sheet name is to not hide
b.Visible = False
End If
Next b
End Sub
答案 2 :(得分:0)
或者,您可以通过错误处理来捕获错误
Sub HideAllSheets()
Dim b As Worksheet
For Each b In Worksheets
On Error Resume Next 'disable error reporting
b.Visible = False
If Err.Number = 1004 Then
MsgBox "The last sheet must stay visible" 'remove if you don't want a message
Exit Sub
End If
On Error GoTo 0 're-enable error handling. Don't forget this line!
Next b
End Sub
答案 3 :(得分:0)
如果您始终希望最后一张纸可见,则可以使用
Sub HideSheets()
Dim i As Long
With ThisWorkbook
For i = 1 To .Sheets.Count - 1
.Sheets(i).Visible = False
Next i
End With
End Sub