尝试从每行拉出第一个字段值时出错

时间:2016-09-30 18:06:02

标签: vba ms-access

AMTSelect是Getrows数组的声明变量变量类型

rCount是一个整数

我正在尝试从每一行中提取第一个字段值,但我不断收到错误,说下标超出了范围。错误发生在for循环中。

代码如下:

If Contractnum <> "" Then
    CNTRecords = "Select Count(*) from [Manual_AINs] WHERE [Manual_AINs].[Contract_Number]= '" & Contractnum & "';"
    Set rs = CurrentDb.OpenRecordset(CNTRecords)
    rCount = rs.Fields(0)
    Set rs = Nothing

        If rCount > 1 Then
            qAMT = "Select [Dollar Amount] from [Manual_AINs] WHERE ((([Manual_AINs].[Contract_Number])='" & Contractnum & "'));"
            Set rs = CurrentDb.OpenRecordset(qAMT)
            AMTSelect = rs.GetRows
            AMTSelectString = "Choose appropriate dollar amount of AIN from the selection below:" & Chr(10) & Chr(10)


            For i = 1 To rCount
                AMTSelectString = AMTSelectString & i & ".)  " & Format(AMTSelect(0, (i - 1)), "$#,##0.00") & Chr(10)
            Next i

1 个答案:

答案 0 :(得分:0)

您没有请求包含.GetRows的任何行 - 这基本上只是调用.GetRows(0),它不会将任何行返回到您的Recordset中。

更改此行...

AMTSelect = rs.GetRows

...为:

AMTSelect = rs.GetRows(rCount)

那就是说,既然你显然试图使用Recordset中的每一行,这就简单得多了:

If Contractnum <> "" Then
    qAMT = "Select [Dollar_Amount] from [Manual_AINs] WHERE [Manual_AINs].[Contract_Number]='" & Contractnum & "';"
    With CurrentDb.OpenRecordset(qAMT)
        If Not .EOF Then .MoveFirst
        AMTSelectString = "Choose appropriate dollar amount of AIN from the selection below:" & Chr(10) & Chr(10)
        Dim i As Long
        Do While Not .EOF
            i = i + 1
            AMTSelectString = AMTSelectString & i & ".)  " & Format$(.Fields(0), "$#,##0.00") & Chr(10)
            .MoveNext
        Loop
    End With
End If