Bru*_*der 13 excel vba listbox
我在Excel工作簿的Sheet1上有一个名为ListBox1的列表框.
每次用户选择列表中的一个项目时,我都需要将其名称复制到名为strLB的变量中.
所以,如果我有Value1,Value2,Value3,Value4并且用户选择了Value1和Value3,我需要我的strLB作为Value1,Value3.非常直截了当.
我尝试用事后做:
For i = 1 To ActiveSheet.ListBoxes("ListBox1").ListCount
If ActiveSheet.ListBoxes("ListBox1").Selected(i) Then strLB = strLB & etc.etc.
Next i
Run Code Online (Sandbox Code Playgroud)
但这非常慢(我的列表框中实际上有15k值).这就是为什么我需要在用户完成输入后实时记录选择而不是循环.
当然,我还需要一种方法来检查用户是否删除了之前的选择.
希望你们能帮忙!
Sid*_*out 12
不幸的是,MSForms列表框循环遍历列表项并检查其Selected属性是唯一的方法.但是,这是另一种选择.我在变量中存储/删除所选项目,你可以在一些远程单元格中执行此操作并跟踪它:)
Dim StrSelection As String
Private Sub ListBox1_Change()
If ListBox1.Selected(ListBox1.ListIndex) Then
If StrSelection = "" Then
StrSelection = ListBox1.List(ListBox1.ListIndex)
Else
StrSelection = StrSelection & "," & ListBox1.List(ListBox1.ListIndex)
End If
Else
StrSelection = Replace(StrSelection, "," & ListBox1.List(ListBox1.ListIndex), "")
End If
End Sub
Run Code Online (Sandbox Code Playgroud)
接受的答案不会削减它,因为如果用户取消选择行,则列表不会相应地更新.
这是我的建议:
Private Sub CommandButton2_Click()
Dim lItem As Long
For lItem = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(lItem) = True Then
MsgBox(ListBox1.List(lItem))
End If
Next
End Sub
Run Code Online (Sandbox Code Playgroud)
由http://www.ozgrid.com/VBA/multi-select-listbox.htm提供