Looping Through Table, Changing Field Values

我们两清 提交于 2019-12-24 17:53:08

问题


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:


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


来源:https://stackoverflow.com/questions/14127325/looping-through-table-changing-field-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!