Looping Through Table, Changing Field Values

2019-08-13 14:14发布

I'm trying to write a piece of code that will run through a table and replace every field that has a certain value with another value.

Private Sub Form_Load()


Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim strSQL As String

Set db = CurrentDb()

strSQL = "SELECT Profile3 FROM Bank WHERE 'AB'"

Set rst = db.OpenRecordset(strSQL, dbOpenDynaset)

Do Until rst.EOF

With rst

If .RecordCount > 0 Then

  .MoveFirst
  .Edit
  !Profile3 = "AA"
  .Update     
  .MoveNext


End If

End With

Loop

End Sub

That's what I'm currently using, however, when it runs it crashes horribly. I know the base code works because when I pull out the loop it works, but only on the first entry.

Like most of the issues I seem to have with VBA, it's probably an absurdly simple fix that I am overlooking.

Thank you for your help.

1条回答
老娘就宠你
2楼-- · 2019-08-13 15:18

You are constantly moving first. You need to get on at some stage. Just get rid of MoveFirst.

Do Until rst.EOF
    With rst
      .Edit
      !Profile3 = "AA"
      .Update     
      .MoveNext
    End With
Loop

In addition, I guess you mean WHERE somefield:

strSQL = "SELECT Profile3 FROM Bank WHERE somefield='AB'"

However, in this case, I suspect what you need is:

strSQL = "UPDATE Bank SET Profile3 ='AA' WHERE Profile3 ='AB'"
CurrentDB.Execute strSQL, dbFailOnError
查看更多
登录 后发表回答