简体   繁体   English

循环浏览VBA中多列列表框的行

[英]Loop through the rows of a multi-column listbox in VBA

I've got a listbox issue. 我有一个列表框问题。 I'm attempting to copy the contents of a multi-column listbox to a collection as arrays of each row of the listbox. 我试图将多列列表框的内容作为列表框每一行的数组复制到集合中。 I realize I could loop through each row and column of the listbox, but I was trying to find a way to return each row of the listbox and assign it directly to the array. 我意识到我可以遍历列表框的每一行和每一列,但是我试图找到一种方法来返回列表框的每一行并将其直接分配给数组。 Something like this: 像这样:

For each item in ListBox
    tempArrayA = item
    tempCollection.add item
Next item

However, when I do that it gives me each individual field of each row rather than the entier row all at once as I'd like it to do. 但是,当我这样做时,它将为我提供每行的每个单独字段,而不是像我希望的那样一次提供整个行。 I've been googling, and I'll keep googling, but I just felt it would be nice to do this by iterating through each item in the listbox rather than selecting each row and then itterating through each column of that row since I have other code that executes upon selection of a row of the listbox. 我一直在使用谷歌搜索功能,但我会继续使用谷歌搜索功能,但是我觉得这样做很不错,方法是遍历列表框中的每个项目,而不是选择每一行,然后遍历该行的每一列,因为我还有其他选择列表框的一行时执行的代码。

Any ideas are, as always, greatly appreciated. 与往常一样,任何想法都将受到高度赞赏。 Thanks! 谢谢!

You can take advantage of the worksheet Index function, the fact that it works on arrays, and the fact that a 0 entered as its Column argument grabs the whole row. 您可以利用工作表的Index函数,它可以在数组上工作以及作为Column参数输入的0占据整个行的事实。 It's really cool!: 这个真的很酷!:

Private Sub UserForm_Activate()
Dim varList As Variant
Dim varRow As Variant
Dim i As Long
Dim tempCollection As Collection

Me.ListBox1.List = ActiveSheet.Range("A2:B20").Value
varList = Me.ListBox1.List
Set tempCollection = New Collection
For i = 1 To Me.ListBox1.ListCount
    varRow = Application.WorksheetFunction.Index(varList, i, 0)
    tempCollection.Add varRow, CStr(i)
    Debug.Print tempCollection(i)(1); " "; tempCollection(i)(2)
Next i
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM