将新位置附加到表单列表框

Appending new positions to a form listbox

我在 Excel 中有一个带有列表框的用户窗体,它必须显示计算结果。问题是当我尝试使用递归循环填充列表框时,先前存在的信息被新数据替换。如何将新信息附加到 ListBox 中的内容而不丢失之前的信息?

我当前的代码:

Dim Form As HistoryFRM, ARR(), i,  ArrHistory()
.....
Set Form = New HistoryFRM
With Form
    .Show vbModeless
    .LBHistory.ColumnCount = 6
    For i = 0 To UBound(ARR)
        ArrHistory = SQL_Editor("SELECT * FROM [Table] WHERE [ID]='" & ARR(i) & "';")
        .LBHistory.Column = ArrHistory
    Next i

End With

试试这个

Option Explicit


    Dim Form As HistoryFRM, ARR() As Variant, ArrHistory() As Variant
    Dim i As Long, j As Long
    ....
    Set Form = New HistoryFRM
    With Form
        .Show vbModeless
        With .LBHistory
            .ColumnCount = 6
            For i = 0 To UBound(ARR)
                ArrHistory = SQL_Editor("SELECT * FROM [Table] WHERE [ID]='" & ARR(i) & "';")
                For j = LBound(ArrHistory) To UBound(ArrHistory)
                    .AddItem ArrHistory(j)
                Next
            Next
        End With
    End With

如果我没理解错的话,您想用从数据库中获取的数组填充六列。 ListCount 属性都会在分配数组时替换其列表的内容。 AddItem 方法允许您将新项目追加到列表中,但仅限于一维。

为了追加一个新的项目数组,我相信您首先需要将当前列表读入一个数组,将新项目追加到该数组,然后将全部写回 ListBox。这是一个例子:

Dim arr()
Dim lb As ListBox
Dim numCols As Long
Dim rowCount As Long, colCount As Long
Dim numNewRecs As Long, newRecCount As Long

Set lb = Me.ListBox1
'You need to know how many new records are coming in
'Substitute this determination here:
numNewRecs = 2
numCols = lb.ColumnCount - 1

'Dimension the array for the current list plus the new records
ReDim arr(lb.ListCount - 1 + numNewRecs, numCols)
'Get the current list
For rowCount = 0 To lb.ListCount - 1
    For colCount = 0 To numCols
        arr(rowCount, colCount) = lb.List(rowCount, colCount)
    Next
Next
'Append the new records
For newRecCount = rowCount To rowCount + numNewRecs - 1
    For colCount = 0 To numCols
        arr(newRecCount, colCount) = "New data" & CStr(newRecCount)
    Next
Next
'Populate the ListBox
lb.List = arr()