重置VBA中的列表框选择

时间:2013-09-06 09:19:49

标签: excel vba excel-vba listbox

我正在尝试在表单关闭时“重置”Excel VBA中的列表框。目前,当我使用userform1.hide函数时,表单消失但是当我使用.show函数再次打开它时,它仍然具有之前的选择。作为一个相对较新的人,任何人都可以帮忙吗?

列表框的代码如下:

Sub CommandButton1_Click()

'Filter by Country
Dim item As Long, dict As Object
Dim wsData As Worksheet

Set wsData = Sheets("TPID")
Set dict = CreateObject("Scripting.Dictionary")

With ListBox1
    For item = 0 To .ListCount - 1
        If .Selected(item) Then dict(.List(item)) = Empty
    Next item
End With

With wsData.ListObjects("Table_ExternalData_1").Range
    .AutoFilter Field:=1
    If dict.Count Then _
        .AutoFilter Field:=1, criteria1:=dict.keys, Operator:=xlFilterValues
End With
'Filter by Continent
Dim item1 As Long, dict1 As Object
Dim wsData1 As Worksheet

Set wsData1 = Sheets("TPID")
Set dict1 = CreateObject("Scripting.Dictionary")

With ListBox2
    For item1 = 0 To .ListCount - 1
        If .Selected(item1) Then dict1(.List(item1)) = Empty
    Next item1
End With

With wsData1.ListObjects("Table_ExternalData_1").Range
    .AutoFilter Field:=4
    If dict1.Count Then _
        .AutoFilter Field:=4, criteria1:=dict1.keys, Operator:=xlFilterValues
End With


End Sub

先谢谢大家,

4 个答案:

答案 0 :(得分:1)

如果您只想清除选择(因为您使用隐藏,而不是卸载),请使用:

me.listbox1.value = ""

如果是多选列表框,则需要使用:

Me.listbox1.MultiSelect = fmMultiSelectSingle
Me.listbox1.Value = ""
Me.listbox1.MultiSelect = fmMultiSelectMulti

这将清除选择,方法是将其设置为仅选择,然后清除选择,然后再将功能设置为多选。

如果要清除整个列表框(您选择的选项),请使用:

Me.listbox1.clear

答案 1 :(得分:1)

尝试使用此代码清除VBA中的列表框

Private Sub clearListBox()
    Dim iCount As Integer

    For iCount = 0 To Me!ListBox1.ListCount
        Me!ListBox1.Selected(iCount) = False
    Next iCount
End Sub

答案 2 :(得分:1)

要重置列表框中选择的明显项目,请尝试:

ListBox1.ListIndex = -1
ListBox2.ListIndex = -1

之后列表框控件中没有明显的项目。

答案 3 :(得分:0)

您可以使用

Private Sub clearListBox()
 'Clears the listbox
    Do Until ListBox1.ListCount = 0
        Me!ListBox1.RemoveItem(0)
    Loop
End Sub