使用VBA在Excel中隐藏和取消隐藏选定的工作表

时间:2012-05-05 06:45:05

标签: excel-vba vba excel

问题: 我希望能够通过表单隐藏和取消隐藏选定的(多个)工作表

可用资源: 有许多可用资源显示如何取消隐藏和隐藏所有工作表但不灵活

说明:

enter image description here

因为sheet5是隐藏的复选框对应于Sheet5被选中。

逻辑/方法:

  • 获取所有工作表的名称,包括隐藏的名称并将其绑定到标签,检查它是隐藏还是取消隐藏,并将其绑定到复选框。

自动创建标签和复选框,标签和复选框以某种方式相互链接,以便程序知道要隐藏和取消隐藏的工作表。

  • 编写代码以检查复选框是否在所选/未选中之间更改其状态。

1 个答案:

答案 0 :(得分:2)

感谢您的所有提示,最后我能够完成这项工作。它可能不是一个好的代码,但它可以工作。

enter image description here

Private Sub btListAllSheets_Click()

With Me.ListBox1

.Clear
.ColumnHeads = True
.ColumnCount = 2
Dim status As String

For i = 1 To Sheets.Count
    If Sheets(i).Visible = xlSheetHidden Then
       status = "Invisible"
    Else
       status = "Visible"
    End If

ListBox1.AddItem (Sheets(i).Name)

ListBox1.List(ListBox1.ListCount - 1, 1) = status

Next i
End With

End Sub

Private Sub bt_hideunhideselectedsheet_Click()

Dim str As String

str = Me.ListBox1.Column(1, Me.ListBox1.ListIndex)


For Each Sh In ThisWorkbook.Worksheets

If Sh.Name = Me.ListBox1.Value And str = "Visible" Then

    Sh.Visible = False

ElseIf Sh.Name = Me.ListBox1.Value And str = "Invisible" Then

    Sh.Visible = True

End If


Next Sh

End Sub

Private Sub btListAllSheets_Click() With Me.ListBox1 .Clear .ColumnHeads = True .ColumnCount = 2 Dim status As String For i = 1 To Sheets.Count If Sheets(i).Visible = xlSheetHidden Then status = "Invisible" Else status = "Visible" End If ListBox1.AddItem (Sheets(i).Name) ListBox1.List(ListBox1.ListCount - 1, 1) = status Next i End With End Sub Private Sub bt_hideunhideselectedsheet_Click() Dim str As String str = Me.ListBox1.Column(1, Me.ListBox1.ListIndex) For Each Sh In ThisWorkbook.Worksheets If Sh.Name = Me.ListBox1.Value And str = "Visible" Then Sh.Visible = False ElseIf Sh.Name = Me.ListBox1.Value And str = "Invisible" Then Sh.Visible = True End If Next Sh End Sub