[英]How do I populate a listbox in excel with a matrix?
I'm trying to populate a listbox in excel with information that is a "matrix"(basically I have some data in the rows and some in the columns. I'm using the code below but I have 2 problems.我正在尝试使用“矩阵”信息填充 excel 中的列表框(基本上我在行中有一些数据,在列中有一些数据。我正在使用下面的代码,但我有 2 个问题。
Dim Rows As Integer
Dim Kolumns As Integer
Dim Start As Range
Set Start = Sheets("sheet1").Range("B2")
Start.Select
Rows = 10
Kolumns = 5
For i = 1 To Rows
For j = 1 To Kolumns
ListBox1.AddItem
ListBox1.List(i - 1, j - 1) = ActiveCell.Offset(i - 1, j - 1).Value
Next j
Next i
The first problem is that the rows is being doubled, if I write "rows = 10" I then get 20 rows.第一个问题是行数加倍,如果我写“rows = 10”,我会得到 20 行。 (The columns work fine). (列工作正常)。
The second problem is my "select".第二个问题是我的“选择”。 I know that it's not the best option to use but I don't know how to avoid it?我知道这不是最好的选择,但我不知道如何避免它?
As already written in the comment, you can use the range variable (in your case Start
) directly to access the content of the cells.正如评论中已经写的那样,您可以直接使用范围变量(在您的情况下为Start
)来访问单元格的内容。
The reason that you get 20 instead of 10 entries in the listbox is that you have the AddItem
within the inner loop, and that is executed 10*2 = 20 times.您在列表框中获得 20 个条目而不是 10 个条目的原因是您在内部循环中有AddItem
,并且执行了 10*2 = 20 次。 You need to move it into the outer loop so that only one item per row is created:您需要将其移动到外部循环中,以便每行只创建一个项目:
Const rowCount = 10
Const colCount = 2
Dim Start As Range
Set Start = ThisWorkbook.Sheets("sheet1").Range("B2")
Dim i As Long, j As Long
For i = 1 To rowCount
ListBox1.AddItem
For j = 1 To colCount
ListBox1.List(i - 1, j - 1) = Start.Offset(i - 1, j - 1).Value
Next j
Next i
Try the next way, please.请尝试下一个方法。 No need of any iteration.不需要任何迭代。 A ListBox
has a List
property which accept an array: ListBox
有一个List
属性,它接受一个数组:
Sub loadListBox()
Dim sh As Worksheet, iRows As Long, Kolumns As Long, Start As Range, arr
Set sh = Sheets("Sheet1")
Set Start = sh.Range("B2")
iRows = 10: Kolumns = 5
arr = sh.Range(Start, Start.Offset(iRows, Kolumns)).Value
With ListBox1
.Clear
.ColumnCount = Kolumns + 1
.list = arr
End With
End Sub
ColumnCount
property which is used to ensure the right number of columns.请注意使用ColumnCount
属性来确保正确的列数。The Code编码
Option Explicit
Sub populateListBox()
Const rCount As Long = 10
Const cCount As Long = 5
Dim cel As Range: Set cel = Sheet1.Range("B2")
With Sheet1.ListBox1
.ColumnCount = cCount
.List = cel.Resize(rCount, cCount).Value
End With
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.