如何用数组填充列表框中的一行? (超过10列)

How fill one row in listbox with array? (more than 10 columns)

我在 UserForm1 中有一个 ListBox1。当我将多行数组发送到 .List 时,一切正常。但是,当我只发送一个单行数组时,ListBox1 中的值在第一列中依次排列。独立使用 Application.Transpose.

我试着写了一个条件和一个for循环,但它不起作用。 运行-时间错误381 无法设置列表 属性。无效 属性 数组索引。 .AddItem无法使用,因为超过了10列

您还有其他解决方案吗?

Dim sumItem As Integer: sumItem = 0 'later between 1 and 5000
.
.
ReDim Preserve arrSort(0 To (columnCount - 1 + 2), 0 To sumItem - 1)
.
.
Call Load(UserForm1) 'to be able to manipulate components
If sumItem = 1 Then 'if only one ROW is loaded in the array
Dim qq As Byte
For qq = 0 To (columnCount - 1)
UserForm1.ListBox1.List(0, qq) = arrSort(qq, 0) 'need to fill the LISTBOX ROW here
Next qq
ElseIf sumItem > 1 Then
UserForm1.ListBox1.List = Application.Transpose(arrSort) 'if more than one ROW is filled, this works
Else
End If
UserForm1.Show

感谢@Tim Williams 这对我有用:

Dim sumItem As Integer: sumItem = 0 'later between 1 and 5000
.
.
ReDim Preserve arrSort(0 To (columnCount - 1 + 2), 0 To sumItem - 1) 'the dimensions are reversed
.
.
Call Load(UserForm1) 'to be able to manipulate components
If sumItem = 1 Then 'if only one ROW is loaded in the array
Dim qq As Byte
Dim arrTmp(0 To 0, 0 To (columnCount - 1)) As Variant 'auxiliary array for dimension exchange
For qq = 0 To (columnCount - 1)
arrTmp(0, qq) = arrSort(qq, 0)
Next qq
UserForm1.ListBox1.List = arrSort
ElseIf sumItem > 1 Then
UserForm1.ListBox1.List = Application.Transpose(arrSort) 'if more than one ROW is filled, this works
Else
End If
UserForm1.Show

你可以这样做:

Const NUM_COLS As Long = 20

Private Sub UserForm_Activate()
    Dim lstInit(0 To 0, 0 To NUM_COLS - 1), r As Long, c As Long
    
    Me.ListBox1.ColumnCount = NUM_COLS
    'fill a row of dummy data....
    For c = 0 To NUM_COLS - 1
        lstInit(0, c) = "R1:C" & (c + 1)
    Next c
    Me.ListBox1.List = lstInit
End Sub

Private Sub CommandButton1_Click()
    Dim arr, c As Long, ub As Long
    arr = AddARow(Me.ListBox1.List) 'get the existing listbox data and add a row
    ub = UBound(arr, 1)
    For c = 0 To UBound(arr, 2)
        arr(ub, c) = "R" & (ub + 1) & ":C" & (c + 1) 'populate the added row
    Next c
    Me.ListBox1.List = arr 'refresh the listbox
End Sub

'add one "row" to a 2D array and return the new array
Function AddARow(lst)
    Dim lstNew, r As Long, c As Long
    ReDim lstNew(0 To UBound(lst, 1) + 1, 0 To UBound(lst, 2))
    'copy existing data
    For r = 0 To UBound(lst, 1)
        For c = 0 To UBound(lst, 2)
            lstNew(r, c) = lst(r, c)
        Next c
    Next r
    AddARow = lstNew
End Function