VBA从Excel中的电子表格中的列表框中获取值

问题描述 投票:13回答:4

我在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

但这非常慢(我的列表框中实际上有15k值)。这就是为什么我需要在用户完成输入后实时记录选择而不是循环。

当然,我还需要一种方法来检查用户是否删除了之前的选择。

希望你们能帮忙!

excel-vba listbox vba excel
4个回答
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

8
投票

接受的答案不会削减它,因为如果用户取消选择行,则列表不会相应地更新。

这是我的建议:

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

http://www.ozgrid.com/VBA/multi-select-listbox.htm提供


0
投票

要获取列表框中所选项的值,请使用以下内容。

对于单列ListBox:ListBox1.List(ListBox1.ListIndex)

对于Multi Column ListBox:ListBox1.Column(column_number, ListBox1.ListIndex)

这避免了循环并且非常有效。


0
投票

选择值:

worksheet name = ordls
form control list box name = DEPDB1

selectvalue = ordls.Shapes("DEPDB1").ControlFormat.List(ordls.Shapes("DEPDB1").ControlFormat.Value)
© www.soinside.com 2019 - 2024. All rights reserved.