Excel VBA:无法从列表框中取消选择ListBox项

时间:2013-03-08 22:36:24

标签: excel-vba vba excel

我有一个命令按钮,用于处理ListBox(ListBox4)中的选定项目。虽然我可以取消选择该命令的Click()过程中的所有项目,但我想,如果用户在ListBox中单击,那么在再次选择之前,取消选择ListBox中的所有内容。

我的代码如下,但它似乎永远不会被调用:

Private Sub ListBox4_Click()
If Apply_Format_Occurred Then
For i = 0 To ListBox4.ListCount - 1
         ListBox4.Selected(i) = False
Next i
End Sub

我是否需要外部命令等来执行此操作?我希望能够像我描述的那样去做。

非常感谢任何帮助!

感谢,

拉​​斯

2 个答案:

答案 0 :(得分:0)

您可以使用ListBox的GotFocus事件,以便在ListBox从用户接收焦点时运行代码。
这是一个示例,显示按钮和ListBox的编码:

Dim Apply_Format_Occurred As Boolean

Private Sub CommandButton1_Click()
    '<other processes>
    Apply_Format_Occurred = True
End Sub

Private Sub ListBox4_Change()
    If Apply_Format_Occurred Then
        For i = 0 To ListBox4.ListCount - 1
             ListBox4.Selected(i) = False
        Next i
        Apply_Format_Occurred = False
    End If
End Sub

答案 1 :(得分:0)

我看到这个帖子很老了,也许有一个简单或更优雅的方法来取消选择列表框项目。但是,我找到了满足我需求的方法。在我的情况下,我希望仅当单击相同的项目时才能取消选择列表框。如果单击了一个新项目,它将被正常选中。我不得不使用两个静态变量(布尔值和“旧选择”占位符)。

可能有一种更简单的方法。但是,我是新手,而且找不到它。希望这可以帮助。将selectedindex设置为-1将取消选择所有内容。 listboxName .ClearSelected()

具有明确和有效的效果。
    Private Sub lstPendingQuotes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstPendingQuotes.Click

    Static blnSelectable As Boolean = True 'use static boolean to retain value between calls
    Static objOldSelected As Object = lstPendingQuotes.SelectedIndex 'use old selected in case a different index is selected

    'if nothing is already selected (as in first form open) allow the selection but change boolean to false and set the OldSelected variable to the current selection
    If blnSelectable Then
        blnSelectable = False
        objOldSelected = lstPendingQuotes.SelectedIndex
    ElseIf lstPendingQuotes.SelectedIndex = objOldSelected Then 'if an item is selected and the same item is clicked un-select all and reset boolean to true for a new possible selection
        lstPendingQuotes.SelectedIndex = -1 'can substitute lstPendingQuotes.ClearSelected()
        blnSelectable = True
    Else 'If a different index is chosen allow the new selection and change boolean to false so if the same item is clicked it will un-select
        objOldSelected = lstPendingQuotes.SelectedIndex
        blnSelectable = False
    End If


End Sub