记录数量返回太多记录

时间:2014-05-21 00:38:23

标签: vba ms-access access-vba ms-access-2013

您好我在MS Access 2013中的表单中有一些vba代码,出于某种原因,当我获得一个记录集时,当数据库真的只有1行并且我已经验证了这一点时它会报告30行。

当我进行调试打印以查看id时,它只是重复30次的相同记录。

以下是运行的代码。

Option Compare Database

Dim selectPlacement As QueryDef
Dim rs As Recordset

Private Sub Form_Current()
    Set selectPlacement = CurrentDb.QueryDefs("SelectPlacement")
    Me.AddPlacementForm.Form.Visible = False

    selectPlacement.Parameters!stu = Me.student_id.Value
    selectPlacement.Parameters!sem = Me.semester_id.Value
    Me.AddPlacementForm.Form!lstStudent.Value = Me.student_id
    Me.AddPlacementForm.Form!cmbSemester.Value = Me.semester_id
    Me.PlacementsBlock1.Form.Filter = "[semester_id]= '" & Me.semester_id.Value & "'"
    Me.PlacementsBlock2.Form.Filter = "[semester_id]= '" & Me.semester_id.Value & "'"
    Me.PlacementsBlock1.Form.FilterOn = True
    Me.PlacementsBlock2.Form.FilterOn = True

    Set rs = selectPlacement.OpenRecordset
    Call SetUpPlacements(rs)
    rs.Close
    Set selectPlacement = Nothing
End Sub

Private Sub SetUpPlacements(rs As Recordset)
    If rs.RecordCount = 0 Then
        Me.PlacementsBlock1.Form.Visible = False
        Me.PlacementsBlock2.Form.Visible = False
        Me.AddPlacementForm.Form.Visible = True
    ElseIf rs.RecordCount = 1 Then
        rs.MoveFirst
        If rs!block = 1 Then
            Me.PlacementsBlock1.Form.Visible = False
        Else
            Me.PlacementsBlock2.Form.Visible = False
        End If
        Me.AddPlacementForm.Form.Visible = True
    Else
        Me.PlacementsBlock1.Form.Visible = True
        Me.PlacementsBlock2.Form.Visible = True
        Me.AddPlacementForm.Form.Visible = False
    End If
End Sub

以下是查询def。

中的查询
SELECT *
FROM student_placements
WHERE (((student_placements.student_id)=[stu]) AND ((student_placements.semester_id)=[sem]));

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:5)

您在没有正确初始化的情况下使用记录集,因此您对rs.RecordCount的调用不会返回正确的值。

您需要通过If rs.EOF and rs.BOF Then检查空记录集。要获得正确的记录计数,您需要致电rs.MoveLast。之前,记录计数不可靠。

有关详细信息,请参阅http://allenbrowne.com/ser-29.html(陷阱3和4)。