如何在多列列表框中获取选定的值

How to get selected value in multicolumn listbox

我的用户窗体中有一个多列列表框,我想获取列表框中 selected 行中元素的所有值。

这是我的用户表单:


就像在照片中,我想 select 一行然后我将单击按钮 Associer 我可以得到这一行的信息。我只能得到第一列 CAN20168301436 我想从整行中获取信息。
我该怎么做?
这是我的按钮点击事件:

Private Sub CommandButton3_Click()
   a = ListBoxResultatFind.Text
End Sub

使用单列,您可以检索如下值:

Dim str as String
str = me.ListBox1.Value

对于多列,您可以像这样检索值:

Dim strCol1 as String
Dim strCol2 as String
Dim strCol3 as String
strCol1 = ListBox1.List(0, 1)
strCol2 = ListBox1.List(0, 2)
strCol3 = ListBox1.List(0, 3)

或者您可以将所有数据添加到 1 个字符串中:

Dim strColumns as String
strColumns = ListBox1.List(0, 1) + " " + ListBox1.List(0, 2) + " " + ListBox1.List(0, 3)

您可以使用此代码

Private Sub CommandButton3_Click()
    Dim strng As String
    Dim lCol As Long, lRow As Long

    With Me.ListBox1 '<--| refer to your listbox: change "ListBox1" with your actual listbox name
        For lRow = 0 To .ListCount - 1 '<--| loop through listbox rows
            If .selected(lRow) Then '<--| if current row selected
                For lCol = 0 To .ColumnCount - 1 '<--| loop through listbox columns
                    strng = strng & .List(lRow, lCol) & " | " '<--| build your output string
                Next lCol
                MsgBox "you selected" & vbCrLf & Left(strng, (Len(strng) - 1)) '<--| show output string (after removing its last character ("|"))
                Exit For '<-_| exit loop
            End If
        Next lRow
    End With
End Sub

无需循环整个列表 - 要获取所选项目行,您可以使用 ListIndex 属性。然后你可以使用 List(Row, Column) 属性 来检索数据,如@DragonSamu 和@user3598756 的示例:

'***** Verify that a row is selected first
If ListBoxResultatFind.ListIndex > -1 And ListBoxResultatFind.Selected(ListBoxResultatFind.ListIndex) Then
    '***** Use the data - in my example only columns 2 & 3 are used
    MsgBox ListBoxResultatFind.List(ListBoxResultatFind.ListIndex, 1) & ":" & ListBoxResultatFind.List(ListBoxResultatFind.ListIndex, 2)
End If

这是一个 6 列列表框,第 3 列是乘数,因此是“(x)”。您也可以根据自己的喜好重新排列列表。

Private Function selList() As String
Dim i As Long

For i =LBound(lstListBox1.List) To UBound(lstListBox1.List)
    If lstListBox1.Selected(i) Then
        selList = selList & lstListBox1.List(i) & " " & lstListBox1.List(i, 1) _
        & "(x" & lstListBox1.List(i, 3) & ")" & " " & lstListBox1.List(i, 2) & " " & lstListBox1.List(i, 4) & ", "
    End If
Next i

If selList= "" Then
    selList= ""
Else
    selList= Left(selList, Len(selList) - 2)
End If

MsgBox selList
End Function