需要帮助以简化查找发生次数的次数

时间:2018-07-12 09:07:51

标签: sql ms-access access-vba

我有此代码 我试图返回第n次出现在我表中的次数 因此,当我在me.id中输入表单时,它将返回此记录是ordernum的第n条记录

    Dim db As DAO.Database
    Dim rs As DAO.Recordset
    Dim ctr As Integer

    Set db = CurrentDb
    Set rs = db.OpenRecordset("SELECT * FROM Table1 WHERE OrderNum =" & Me.OrderNum, dbOpenDynaset)

    ctr = 0

    With rs

      .MoveLast
      .MoveFirst

         Do Until .EOF
            ctr = ctr + 1
            If rs!ID = Me.ID Then
                MsgBox ctr
            End If
            .MoveNext
         Loop

   End With

这是我的桌子

enter image description here

因此,当我输入Ordernum 300000122和ID 4时,它将返回2(第二次出现)

1 个答案:

答案 0 :(得分:1)

您只需计算ID为<=(您想要的ID)

x = DCount("*", "Table1", "OrderNum =" & Me.OrderNum & " AND ID <= " & Me.ID)