MS Access VBA .additem到列表框下标超出范围错误

时间:2018-10-16 13:52:03

标签: ms-access access-vba

尝试根据组合框中的选择将值添加到列表框时出现错误。我为记录集添加的filter(?)并没有告诉lngRows仅在应用过滤器后才使用那些项,而我认为这是问题的一部分。添加时出错,将值放在框中,然后由于添加空格而出错。有办法解决这个问题吗?

Private Sub Combo5_AfterUpdate()
Set lb = Me.lbSA.Object

    Dim varSelection() As Variant
    Dim i As Long

    lngRows = CurrentDb.TableDefs("tblSA").RecordCount
    varSelection = CurrentDb.OpenRecordset("SELECT PROJ_ID,ShipArea FROM tblSA WHERE PROJ_ID = '" & Me.Combo5.Column(1) & "'").GetRows(lngRows)

    For i = 0 To lngRows - 1
        Me.lbSA.AddItem (varSelection(0, i)) 'error is here
        Me.lbSA.Column(1, i) = varSelection(1, i)
    Next
End Sub

1 个答案:

答案 0 :(得分:0)

不需要数组或列表框对象:

Private Sub Combo5_AfterUpdate()
    Dim varSelection As Recordset
    Set varSelection = CurrentDb.OpenRecordset("SELECT PROJ_ID, ShipArea FROM tblSA WHERE PROJ_ID = '" & Me.Combo5.Column(1) & "'")
    While Not varSelection.EOF
        Me.lbSA.AddItem varSelection(0), 0
        varSelection.MoveNext
    Wend
End Sub

或仅设置RowSource属性。确保将RowSourceType属性设置为“表/查询”。

Private Sub Combo5_AfterUpdate()
    Me.lbSA.RowSource = "SELECT PROJ_ID, ShipArea FROM tblSA WHERE PROJ_ID = '" & Me.Combo5.Column(1) & "'")
End Sub