Home » excel » Correct syntax for SQL Update function in Excel VBA

Correct syntax for SQL Update function in Excel VBA

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am trying to use the SQL Update, SET and Where query using variables in excel VBA. I can create the string to update one query but for multiple columns it is proving more difficult. Please can someone point me in the right direction?      

con.Execute "UPDATE [Maint_Record] SET [Completed_] ='" & strCompleted & "'" & "Where [ID] = '" & intID & "'"

The above line of code works well for the ‘completed_’ column. But when I need to update three more columns and the code below doesn’t work!

con.Execute "UPDATE [Maint_Record] SET [Priority_] ='" & strPriority & "'," [Assigned_To] ='" & strAssignedTo & "', " [Comments_] ='" & strComments & "', " [Completed_] ='" & strCompleted & "'" & "Where [ID] = '" & intID & "';"

I am getting end of statement warnings and the like from Excel 🙁 Please can someone help? I’m so close to getting this working, but not close enough 🙂

How to&Answers:

You have problems with your string – you have included extra quotes (") where you don’t want them. See them highlighted below with X:

                 X
strPriority & "'," [Assigned_To] =

                    X
strAssignedTo & "', " [Comments_] =

                  X
strComments & "', " [Completed_] =

You need to take another look at this string and correct the issue with it, giving you something like:

con.Execute "UPDATE [Maint_Record] SET [Priority_] ='" & strPriority & "', [Assigned_To] ='" & strAssignedTo & "', [Comments_] ='" & strComments & "', [Completed_] ='" & strCompleted & "' Where [ID] = '" & intID & "';"

Your final WHERE statement is:

Where [ID] = '" & intID & "';"

If intID is a number (int) then you don’t need the single-quotes:

Where [ID] = " & intID & ";"