我有我的用户界面中的多列列表框,我想获取列表框中所选行中元素的所有值。
这是我的用户窗体:如何获得多列列表框中的选定值
就像在照片中,我要选择一条线,然后我会点击按钮Associer
和我能得到该行的信息。我可以得到的第一列是CAN20168301436
我想从整个行中获取信息。
我该怎么做?
这里是我的按钮点击事件:
Private Sub CommandButton3_Click()
a = ListBoxResultatFind.Text
End Sub
我有我的用户界面中的多列列表框,我想获取列表框中所选行中元素的所有值。
这是我的用户窗体:如何获得多列列表框中的选定值
就像在照片中,我要选择一条线,然后我会点击按钮Associer
和我能得到该行的信息。我可以得到的第一列是CAN20168301436
我想从整个行中获取信息。
我该怎么做?
这里是我的按钮点击事件:
Private Sub CommandButton3_Click()
a = ListBoxResultatFind.Text
End Sub
您可以使用此代码
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
与单个列可以检索如下价值:
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)
感谢您的效应初探,我测试,它可以只得到CAN20168301436但无法获得全部的信息,这是一个多Colonne的列表框 –
@YiaoSun多少列? – DragonSamu
它有7个colonnes –
无需循环整个列表 - 为了让你可以使用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
你测试过了吗?在我到2013年的Excel VBA中,如果没有选择任何项目,那么多列ListBox属性的ListIndex属性将返回0,就像第一个项目一样。这就是为什么我遍历行并检查“Selected”属性。另一种方法是对'0''ListIndex'进行双重检查,如'If .ListIndex = 0和.Selected(0)或.ListIndex> 0 Then',但是对于第二次代码复审 – user3598756
@YiaoSun似乎太不清楚了:根据我以前的评论,您可能想要针对可能的_no-selection_场景来测试此解决方案 – user3598756
@ user3598756没有选择会给出ListIndex = -1,这就是我测试ListIndex> -1的原因。 (我使用Excel 2010,它的工作方式就像一个魅力!) –
这是一个6column列表框和第三列将是事半功倍因此“(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
_brave_ downvoter会显示并给出任何解释,以便让人们知道他们为什么不应该遵循答案并教我如何改进? – user3598756