ListBox.Selected无法正常工作;运行时错误'-2147024809(80070057)

时间:2019-08-13 18:45:24

标签: excel vba listbox hide

尝试在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

1 个答案:

答案 0 :(得分:0)

列表框计数从零开始,因此当您选择列表中的第一个项目时,它永远不会到达,但是对于Sheets从1开始,因此您必须始终将1添加到列表框索引中。

编辑:

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

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

enter image description here