VBA MS Access循环:如何定义将当前记录与上一个记录进行循环比较的IF语句

时间:2019-05-18 23:04:31

标签: access-vba recordset

我想遍历一个记录集并弄清楚值是否有重大变化,例如从一个记录到其他记录的+/- 10%。 我的问题是我不知道如何引用上一条记录...或将其与下一条记录进行比较.....

这里是Recordset的想法

Month_Year Price
01.2019 112.85
02.2019 145.25 (here the price jumped up more then 10% --> Msg "Check....")
03.2019 147.45

rs1.MoveFirst

Do Until rs1.EOF

******** HERE I NEED HELP:

     IF  
     rs1.currentrecord???? / rs1.previousrecord???? between 0.9 and 1.1 THEN

    rs1.Edit

       rs1!Comments = "Check if Index is correct"
    rs1.Update
 End If

rs1.MoveNext
Loop

2 个答案:

答案 0 :(得分:1)

可能是这样的:

Dim CurrentPrice  As Currency
Dim PreviousPrice As Currency

rs1.MoveFirst

Do Until rs1.EOF
    CurrentPrice = rs1!Price.Value
    If PreviousPrice > 0 Then
       If CurrentPrice / PreviousPrice >= 1.1 Or
           CurrentPrice / PreviousPrice <= 0.9 Then
           rs1.Edit 
               rs1!Comments.Value = "Check if Index is correct"
           rs1.Update
       End If 
    End If
    PreviousPrice = CurrentPrice
    rs1.MoveNext
Loop

rs1.Close

答案 1 :(得分:0)

非常感谢donPablo和Gustav。我可以在您的帮助下解决问题:

Function Mailings()
Dim rs1 As DAO.Recordset
Dim db As Database
Dim StrSql1 As String
Dim CurrentPrice  As Single
Dim PreviousPrice As Single

Set db = CurrentDb
StrSql1 = "SELECT * " & _
          "FROM IAZI_Index " & _
          "ORDER BY JahrT ASC;"

Set rs1 = db.OpenRecordset(StrSql1)


rs1.MoveFirst
Do Until rs1.EOF

If rs1.BOF = True Then
    PreviousPrice = rs1!SI_Condominium_PR.Value

Debug.Print rs1!SI_Condominium_PR

    rs1.MoveNext
End If

Debug.Print rs1!SI_Condominium_PR

    CurrentPrice = rs1!SI_Condominium_PR.Value



               If PreviousPrice > 0 Then
            If CurrentPrice / PreviousPrice >= 1.03 Or CurrentPrice / PreviousPrice <= 0.97 Then

        rs1.Edit
        rs1!Comments = "Check if Index is correct"
        rs1.Update


            End If
        End If

        PreviousPrice = CurrentPrice

        rs1.MoveNext
Loop


rs1.Close
Set rs1 = Nothing
Set db = Nothing


End Function