对于一些人来说,这可能是一个便宜的问题,但我对如何填充我的列表框感到困惑。
使用此行我可以填充列表框,如下所示:
ListBox1.List = Sheets("Sheet1").Cells(1, 1).CurrentRegion.Value
或
Dim rngName As Range
Dim ws As Worksheet
Dim i As Integer
Set ws = Worksheets("Sheet1")
For i = 1 To ws.Cells(ws.Rows.Count, 1).End(xlUp).Row Step 1
If ws.Cells(i, 1).Value <> vbNullString Then Me.ListBox1.AddItem
ws.Cells(i, 1).Value
Next i
以下是我计划用于填充列表框并且是渐进式的数据。只有列具有修复计数。
有人请教我如何使用 FOR LOOP 填充适用于多个列和行的列表框,如上面的代码所示。任何帮助赞赏。感谢。
答案 0 :(得分:5)
<强>方法强>
ListBox1.List
(方法相同,但反方向)。<强>代码强>
Private Sub CommandButton1_Click()
' Purpose: fill listbox with range values after clicking on CommandButton1
' (code could be applied to UserForm_Initialize(), too)
' Note: based on @Siddharth-Rout 's proposal at https://stackoverflow.com/questions/10763310/how-to-populate-data-from-a-range-multiple-rows-and-columns-to-listbox-with-vb
' but creating a variant data field array directly from range in a one liner
' (instead of filling a redimensioned array with range values in a loop)
Dim ws As Worksheet
Dim rng As Range
Dim MyArray ' variant, receives one based 2-dim data field array
'~~> Change your sheetname here
Set ws = Sheets("Sheet1")
'~~> Set you relevant range here
Set rng = ws.Range("A1:C" & ws.Range("A" & ws.Rows.Count).End(xlUp).Row)
With Me.ListBox1
.Clear
.ColumnHeads = False
.ColumnCount = rng.Columns.Count
'~~> create a one based 2-dim datafield array
MyArray = rng
'~~> fill listbox with array values
.List = MyArray
'~~> Set the widths of the column here. Ex: For 5 Columns
'~~> Change as Applicable
.ColumnWidths = "50;50;50"
.TopIndex = 0
End With
End Sub
其他提示
数组方法的另一个优点 - 当使用.AddItem
方法时,它克服仅 10列的内置限制。
此外,请记住列表框索引是零基于,因此例如,您获得第一个项目行的电子邮件地址(第3列,索引2)(索引0) )via ListBox1.List(0, 2)
,而数据字段数组自动成为一个基于2的dim数组。
您不限于使用.List
方法从列表框中获取信息,您可以使用ListBox1.Column" or even create a new array out of it, which remains a 2-dim object, even if there is only ONE item (note: the
Application.Transpose`方法反转行 - 列顺序一个2维数组,只有一行到1-dim数组。)
最后一点:您可以通过rng = ListBox1.List
轻松地将整个列表框转储回Excel表格,但要注意定义正确的范围。