ListBox.Selected 不工作; 运行-时间错误'-2147024809(80070057)

ListBox.Selected is not working; Run-time error '-2147024809(80070057)

如果在 ListBox 中选择,则尝试创建隐藏或取消隐藏工作表。 ListBox.Selected(c) 表示无法选择 属性。它有 运行 时间错误,如果我结束而不是调试,它会隐藏或取消隐藏一些工作表。

我尝试使用 ListIndexListValue 而不是 ListCount,但它没有任何用处!

Private Sub CommandButton1_Click()
Dim str As String
Dim Status As String

With ListBox1

Dim C As Long
For C = 1 To ListBox1.ListCount

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


If ListBox1.Selected(C) = True And str = "Visible" Then
Sheets(C).Visible = False

ElseIf ListBox1.Selected(C) = False And str = "Visible" Then
Sheets(C).Visible = True
End If

If ListBox1.Selected(C) = True And str = "Invisible" Then
Sheets(C).Visible = True

ElseIf ListBox1.Selected(C) = False And str = "Invisible" Then
Sheets(C).Visible = False
End If

Next C
Unload Me
End With

End Sub

选中列表框项目后,点击命令按钮会将工作表可见性状态从隐藏更改为取消隐藏,反之亦然。ListBox

Listbox 计数从零开始,因此当您 select 例如列表中的第一项时,它永远不会到达,但是对于 Sheets 从 1 开始,因此您需要始终将 1 添加到 ListBox 索引达到它。

编辑:

Private Sub CommandButton1_Click()

    Dim c As Long
    dim intListCount as Long

    intListCount = Me.ListBox1.ListCount - 1

    For c = 0 To intListCount

        ThisWorkbook.Sheets(c + 1).Visible = IIf(Me.ListBox1.Selected(c) And Me.ListBox1.List(c, 1) = "Visible", False, True)

    Next c

    Unload Me

End Sub

Private Sub UserForm_Initialize()

    Dim ws As Worksheet

    i = 0
    For Each ws In ThisWorkbook.Worksheets

        Me.ListBox1.AddItem
        Me.ListBox1.List(i, 0) = ws.Name
        Me.ListBox1.List(i, 1) = IIf(Not ws.Visible, "Hidden", "Visible")

    i = i + 1
    Next ws

End Sub

请注意,当您尝试隐藏工作簿中的所有可用工作表时,可能会提示错误。