如何用矩阵填充 excel 中的列表框?

How do I populate a listbox in excel with a matrix?

我正在尝试用“矩阵”信息填充 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

第一个问题是行被加倍了,如果我写“rows = 10”我就会得到 20 行。 (列工作正常)。

第二个问题是我的“select”。我知道这不是最好的选择,但我不知道如何避免它?

如评论中所述,您可以直接使用范围变量(在您的情况下 Start)来访问单元格的内容。

您在列表框中得到 20 个而不是 10 个条目的原因是您在内部循环中有 AddItem,并且执行了 10*2 = 20 次。您需要将它移到外循环中,以便每行只创建一个项目:

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

请尝试下一种方法。不需要任何迭代。 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 属性 的使用,它用于确保正确的列数。

代码

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