Solved

Executing an update query using VBA code

Posted on 2016-09-21
5
70 Views
Last Modified: 2016-09-21
I'm a bit of a novice and I'm having a hard time getting something to work.

I have a form with dropdowns.  Once the dropdowns are selected I need an update query to use the selections in the dropdowns to update some cells in some tables.  Some of the dropdowns on the form feed the WHERE criteria, and some feed the "Update To" part.

I've built a separate update query that works great.  But trying to embed the query or trying to execute the query in VBA code (via an On Click sub for a button on the form) results in a slew of different errors.  The most common is a 3601:

"Run-time error '3061'. Too few parameters. Expected 1."

This didn't work:

CurrentDb.Execute "MyUpdateQuery"

Open in new window


Also didn't work:  

 DoCmd.RunSQL  "UPDATE Results INNER JOIN SampleDetails ON (Results.Test = SampleDetails.Test) AND (Results.SampleNumber = SampleDetails.SampleNumber) AND (Results.OrderID = SampleDetails.OrderID) SET SampleDetails.SampleDetails_User4 = Date() & "--" & BEUser(), Results.Results_User1 = [Forms]![Rework]![ReworkCombo], Results.Results_User2 = [Forms]![Rework]![InitiatorCombo], Results.Results_User3 = [Forms]![Rework]![ReasonTextBox]" _
& "WHERE (((SampleDetails.SampleNumber)=[Forms]![Rework]![SampleNumCombo]) AND ((SampleDetails.Test)=[Forms]![Rework]![TestCombo]) AND ((Results.Param)=[Forms]![Rework]![ParamCombo]));"

Open in new window


My update query works great.  It's:

UPDATE Results INNER JOIN SampleDetails ON (Results.Test = SampleDetails.Test) AND (Results.SampleNumber = SampleDetails.SampleNumber) AND (Results.OrderID = SampleDetails.OrderID) SET SampleDetails.SampleDetails_User4 = Date() & "--" & BEUser(), Results.Results_User1 = [Forms]![Rework]![ReworkCombo], Results.Results_User2 = [Forms]![Rework]![InitiatorCombo], Results.Results_User3 = [Forms]![Rework]![ReasonTextBox]
WHERE (((SampleDetails.SampleNumber)=[Forms]![Rework]![SampleNumCombo]) AND ((SampleDetails.Test)=[Forms]![Rework]![TestCombo]) AND ((Results.Param)=[Forms]![Rework]![ParamCombo]));

Open in new window


So how do I get a button on a form to execute an existing update query without these maddening error messages?
0
Comment
Question by:BugHugger
5 Comments
 
LVL 31

Expert Comment

by:Helen_Feddema
ID: 41809306
Could be a problem with the form reference.  Can you save the form values to public variables or custom database properties for use in the queries?  This tends to be more reliable.  Here is some code for working with custom database properties:

Option Compare Database
Option Explicit

Private dbs As DAO.Database
Private prp As DAO.Property
Private prps As DAO.Properties


Public Sub SetProperty(strName As String, lngType As Long, _
   varValue As Variant)
'Created by Helen Feddema 2-Oct-2006
'Modified by Helen Feddema 11-Oct-2014
'Called from various procedures

On Error GoTo ErrorHandler

   'Attempt to set the specified property
   Set prps = CurrentDb.Properties
   prps(strName) = varValue

ErrorHandlerExit:
   Exit Sub

ErrorHandler:
    If Err.Number = 3270 Then
      'The property was not found; create it
      Set prp = CurrentDb.CreateProperty(Name:=strName, _
         Type:=lngType, Value:=varValue)
      CurrentDb.Properties.Append prp
      Resume Next
   Else
   MsgBox "Error No: " & Err.Number _
      & " in SetProperty procedure; " _
      & "Description: " & Err.Description
      Resume ErrorHandlerExit
   End If

End Sub

Public Function GetProperty(strName As String, strDefault As String) _
   As Variant
'Created by Helen Feddema 2-Oct-2006
'Modified by Helen Feddema 11-Oct-2014
'Called from various procedures

On Error GoTo ErrorHandler
   
   'Attempt to get the value of the specified property
   GetProperty = CurrentDb.Properties(strName).Value

ErrorHandlerExit:
   Exit Function

ErrorHandler:
   If Err.Number = 3270 Then
      'The property was not found; use default value
      GetProperty = strDefault
      Resume Next
   Else
      MsgBox "Error No: " & Err.Number _
         & " in GetProperty procedure; " _
         & "Description: " & Err.Description
      Resume ErrorHandlerExit
   End If

End Function

Public Function ListCustomProps()
'Created by Helen Feddema 3-Oct-2006
'Modified by Helen Feddema 3-Oct-2006
'Lists DB properties created in code (as well as built-in properties)

On Error Resume Next
   
   Set dbs = CurrentDb
   Debug.Print "Database properties:"
   
   For Each prp In dbs.Properties
      Debug.Print vbTab & prp.Name & ": " & prp.Value
   Next prp

End Function

==================================
Usage examples:

Private dbs As DAO.Database
Private prp As DAO.Property
Private prps As DAO.Properties
Private lngDataType As Long
Private strPropertyName As String
Private strPropertyValue as String
Private varPropertyValue As Variant

Date
====
   If IsDate(Me![txtStartDate].Value) = False Then
      strTitle = "Invalid date"
      strPrompt = "Please enter a valid start date"
      Me![txtStartDate].SetFocus
      MsgBox prompt:=strPrompt, _
         buttons:=vbExclamation + vbOKOnly, _
         Title:=strTitle
      GoTo ErrorHandlerExit
   Else
      dteStart = CDate(Me![txtStartDate].Value)
   End If
   
   strPropertyName = "PropName"
   lngDataType = dbDate
   Call SetProperty(strPropertyName, lngDataType, dteStart)

   GetStartDate = CDate(GetProperty("PropName", ""))

Text
====
   strPropertyName = "PropName"
   strPropertyValue = CStr(cbo.Value)
   lngDataType = dbText
   Call SetProperty(strPropertyName, lngDataType, _
      strPropertyValue )

   strDocsPath = GetProperty("PropName", "")

Long
====
   strPropertyName = "PropName"
   lngDataType = dbLong
   Call SetProperty(strPropertyName, lngDataType, lngID)

   lngID = CLng(GetProperty("PropName", ""))

Integer
=======
   strPropertyName = "PropName"
   lngDataType = dbInteger
   Call SetProperty(strPropertyName, lngDataType, intMonth)

   intID = CInt(GetProperty("PropName", ""))

Boolean
=======
   strPropertyName = "PropName"
   lngDataType = dbBoolean
   Call SetProperty(strPropertyName, lngDataType, "True")

   blnValue = CBln(GetProperty("PropName", ""))


Saving to a custom property from a control's AfterUpdate event
==============================================================
Private Sub txtDate_AfterUpdate()
'Created by Helen Feddema 2-Sep-2009
'Last modified 2-Sep-2009

On Error GoTo ErrorHandler
   
   If IsDate(Me![txtDate].Value) = True Then
      dteSingle = CDate(Me![txtDate].Value)
      strPropertyName = "SingleDate"
      Call SetProperty(strName:=strPropertyName, _
         lngType:=dbDate, varValue:=dteSingle)
   End If
   
ErrorHandlerExit:
   Exit Sub

ErrorHandler:
   MsgBox "Error No: " & Err.Number & "; Description: " & _
      Err.Description
   Resume ErrorHandlerExit

End Sub

Open in new window

0
 
LVL 50

Accepted Solution

by:
Rgonzo1971 earned 500 total points
ID: 41809321
Maybe
DoCmd.RunSQL  "UPDATE Results INNER JOIN SampleDetails ON (Results.Test = SampleDetails.Test) AND (Results.SampleNumber = SampleDetails.SampleNumber) AND (Results.OrderID = SampleDetails.OrderID) SET SampleDetails.SampleDetails_User4 = Date() & ""--"" & BEUser(), Results.Results_User1 = [Forms]![Rework]![ReworkCombo], Results.Results_User2 = [Forms]![Rework]![InitiatorCombo], Results.Results_User3 = [Forms]![Rework]![ReasonTextBox]" _
& "WHERE (((SampleDetails.SampleNumber)=[Forms]![Rework]![SampleNumCombo]) AND ((SampleDetails.Test)=[Forms]![Rework]![TestCombo]) AND ((Results.Param)=[Forms]![Rework]![ParamCombo]));

Open in new window

0
 

Author Closing Comment

by:BugHugger
ID: 41809337
It works!

Thank you, Rgonzo!
0
 
LVL 36

Expert Comment

by:PatHartman
ID: 41809353
The execute method didn't work because the query includes parameters (form field references) and those parameters must be set first so you need to use a slightly different technique.

When you are building SQL strings in VBA, it is best to actually create a variable to hold them, that is if you are fond of your hair.

Dim strSQL as String
strSQL =  "UPDATE Results as r INNER JOIN SampleDetails as s ON (r.Test = s.Test) AND (r.SampleNumber = s.SampleNumber) AND (r.OrderID = s.OrderID) SET s.SampleDetails_User4 = Date() & '--"
strSQL = strSQL & BEUser() & "', r.Results_User1 = '" & [Forms]![Rework]![ReworkCombo] & "', r.Results_User2 = '" & [Forms]![Rework]![InitiatorCombo] & "', r.Results_User3 = '"
strSQL = strSQL & [Forms]![Rework]![ReasonTextBox] & "'"
strSQL = strSQL & " WHERE s.SampleNumber = " & [Forms]![Rework]![SampleNumCombo] & " AND s.Test = " & [Forms]![Rework]![TestCombo] & "  AND s.Param = [Forms]![Rework]![ParamCombo] & ";"

 DoCmd.RunSQL  strSQL

Print out the strSQL before you execute the query and post it here if you get any syntax errors.  It is hard to type long strings like this and get all the quotes, etc in the correct spot.  I also had to decide what data type certain values were and if I chose wrong, you will need to correct them.

Text values need to be embedded in single quotes.  Numeric values do not.  Dates (I didn't see any) need to be embedded in #'s.
0
 
LVL 36

Expert Comment

by:PatHartman
ID: 41809365
I see that BugHugger beat me to the punch.  I will leave my answer and explain the difference.

the embedded parameters work in docmd.runSQL because this is an Access VBA command and so the VBA expression engine is available to build the string.  The .execute method is DAO and doesn't have the VBA expression engine so you either need to specificallly set the parameters or build the string in such a way (as I did) that takes advantage of the expression engine.

Most experts will choose to use the DAO .execute method rather than the RunSQL method so even though you have accepted an answer, this additional solution may help someone else.
0

Featured Post

Three Reasons Why Backup is Strategic

Backup is strategic to your business because your data is strategic to your business. Without backup, your business will fail. This white paper explains why it is vital for you to design and immediately execute a backup strategy to protect 100 percent of your data.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I see at least one EE question a week that pertains to using temporary tables in MS Access.  But surprisingly, I was unable to find a single article devoted solely to this topic. I don’t intend to describe all of the uses of temporary tables in t…
A simple tool to export all objects of two Access files as text and compare it with Meld, a free diff tool.
Familiarize people with the process of utilizing SQL Server stored procedures from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Micr…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

679 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question