0

How should I write the name of the recordset correctly? I have a type mismatch error on & rsg & at "sq3=..." line. Thanks in advance.

Dim rsG As DAO.Recordset
Dim sq2, sq3 As String

sq2 = "SELECT * from GeneralTable "
sq2 = sq2 & "where gsede='LION' and (gExclu is null) and (gAda is  null) "
sq2 = sq2 & "order by gnomb,gnif;"

Set rsG = CurrentDb.OpenRecordset(sq2)

sq3 = "UPDATE " & rsG & " SET gsede ='AA' WHERE gsede='LION'"

DoCmd.RunSQL (sq3)
1
  • It looks like you have three very useful answers to your question(s). And because you're fairly new to SO I thought I'd point out that it's very useful to others if you provide them with feedback. Upvoting answers can be done by clicking the up arrow and that tells them that their answer was useful to you. We all appreciate the little things in life. If you can select one answer as the best check it off. More feedback and it helps to close off questions as answered. Enjoy your SO stay... Commented Aug 7, 2016 at 13:53

3 Answers 3

3

You are mixing up totally different ways to update data - UPDATE SQL and VBA recordset.

If you want to update a recordset row by row, you do something like

Do While Not rsG.EOF
    If rsG!foo = "bar" Then
        rsG.Edit
        rsG!gsede = "AA"
        rsG.Update
    End If
    rsG.MoveNext
Loop
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I know it. My original code was with a loop, like you say. All the code was write using vba recordset. But I had this idea: why not to change all loop lines for only one with sql update? ...
2

Do the update using a single query:

update generaltable
    set gsede = 'AA'
    where gsede ='LION' and (gExclu is null) and (gAda is  null);

If you do the update off of rsG, then you'll likely do a separate update for each row, and that is inefficient.

1 Comment

Thanks, it's only a example, I know that this code do twice the same. My question is how to write correctly the recordset variable name into a SQL string without compilation error.
2

You can't mix and match SQL and recordset objects. You can either build a full update statement that includes the logic of the first select (as other answer suggests), or you can open a dynamic recordset and loop through the records programmatically to make the updates.

That being said, looping through large recordsets programmatically to make updates is usually better handled by a bulk SQL statement, unless it is essential to consider each row individually inside the code - which in your basic example would not be the case.

MS has a good article on the DAO.Recordset object. There is a dynamic-type Recordset example about halfway down.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.