将新位置添加到表单列表框中

时间:2018-02-14 13:44:35

标签: vba excel-vba userform excel

我在Excel中有一个带有ListBox的UserForm,它必须显示计算结果。问题是当我尝试使用递归循环填充列表框时,之前的信息将被新数据替换。如何将新信息附加到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

2 个答案:

答案 0 :(得分:0)

试试这个

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

答案 1 :(得分:0)

如果我理解正确,您希望用数据库中的数组填充六列。分配数组时,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()