I am creating a new query in MS Access that updates an existing record based on the “Branch” and “Employee” fields. How can I set the criteria to reference cell values? Say
A2 holds the “Branch” ID for Access and
B2 holds the value for the “Employee” ID in Access.I want to update my Access “Notes” Field. My query works when running in Excel, but only because I have specified what the “Employee” & “Branch” ID’s are. Nothing updates when i run my code below:
Sub modify_record() Dim ac As Object Dim branchid As String Dim employeeid As String Dim notesF As String Set ac = CreateObject("Access.Application") branchid = Sheets("Sheet4").Range("A2") employeeid = Sheets("Sheet4").Range("B2") notesF = Sheets("Sheet4").Range("C2") Dim strDatabasePath As String strDatabasePath = "C:\Users\johnsmith\OneDrive\pbsbackup.mdb" With ac .OpenCurrentDatabase (strDatabasePath) Dim db As Object Set db = .CurrentDb db.Execute "Update_Records" End With End Sub
Query in MS Access. Saved as Update_Records
UPDATE pbsmaster SET pbsmaster.notes = "notesF" WHERE (((pbsmaster.branch)="branchid") AND((pbsmaster.employee)="employeeid"));
Your variables don’t magically transfer into the query, just because they have the same name.
You need to specify the parameters in the Access query, and pass them via a
DAO.QueryDef object in the Excel VBA code.
Here is an example: https://stackoverflow.com/a/2317225/3820271
Dim qd As Object ' DAO.QueryDef Set qd = db.QueryDefs("Update_Records") qd.Parameters("branchid") = branchid ' etc. qd.Execute
Here is my solution from what I learned from @Andre. I am able to execute my code, I noticed working with Parameters is much quicker than opening a recordset with DAO.
Sub foo() Dim db As Database Dim qdf As QueryDef Set db = OpenDatabase("C:\Users\employee\OneDrive\samplefile.mdb") Set qdf = db.CreateQueryDef("", _ "PARAMETERS pbsbranch text , pbsnotes text; " & _ "UPDATE pbsmaster SET pbsmaster.notes=[pbsnotes] " & _ "WHERE pbsmaster.branch=[pbsbranch] " & _ "") qdf!pbsbranch = Sheets("Sheet4").Range("A2") qdf!pbsnotes = Sheets("Sheet4").Range("C2") qdf.Execute dbFailOnError Set qdf = Nothing Set cdb = Nothing End Sub