Using QDEF in VBA - vba

I am trying to update a local table in an Access database using a value passed from a click event. I want to add checkmarks to a column in the table for all the same values as the record that was clicked. What am I doing wrong with the QDEF?
Public Sub addcheckmarks(functionLocation As String)
Dim strsql As String
Dim qdef As QueryDef
strsql = "PARAMETERS [CheckLocation] String; UPDATE tbl_TMP_inventory set addlocation = -1 where Location = [CheckLocation]"
Set qdef = CurrentDb.createQueryDefs("", strsql)
qdef!CheckLocation = functionLocation
qdef.Execute dbFailOnError
End Sub

You don't have to build a temporary query for a simple update:
Public Sub addcheckmarks(functionLocation As String)
Dim strsql As String
strsql = "UPDATE tbl_TMP_inventory SET addlocation = True WHERE Location = '" & functionLocation & "'"
CurrentDb.Execute strsql
End Sub

Related

Access VBA run query with values passed from a list box

I have made this form in Access and I am hoping to do the following task.
The list box here contains two columns, and can be multi-selected. I want to use the values second column (the right column) and pass them into a query that I set up for the "test2" button below.
And here is my VBA code for the on-click event for the button.
Private Sub test2_Click()
Dim db As dao.Database
Dim qdef As dao.QueryDef
Dim strSQL As String
Set db = CurrentDb
'Build the IN string by looping through the listbox
For i = 0 To Select_Counties2.ListCount - 1
If Select_Counties2.Selected(i) Then
strIN = strIN & "'" & Select_Counties2.Column(1, i) & "',"
End If
Next i
'Create the WHERE string, and strip off the last comma of the IN string
strWhere = " WHERE County_GEOID in " & "(" & Left(strIN, Len(strIN) - 1) & ")"
strSQL = strSQL & strWhere
Set qdef = db.CreateQueryDef("User query results", strSQL)
qdef.Close
Set qdef = Nothing
Set db = Nothing
DoCmd.OpenQuery "User query results", acViewNormal
End Sub
I was getting this error:
Can someone tell me what I did wrong in the code? Thank you!
In this example from microsoft they call application.refreshwindow without explanation.
https://learn.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/database-createquerydef-method-dao
What I think is going on is that your code fails because access cannot find the query that was just added to it's collection of queries. Also your generated sql is no longer valid.
So: replace my sql with your own valid sql
Private Sub test2_Click()
Dim db As DAO.Database
Dim qdef As DAO.QueryDef
Dim strSQL As String
strSQL = "PARAMETERS GEOID Number; " 'without valid sql this code doesn't run so
'replace my sql with your own.
strSQL = strSQL & "SELECT GEOID FROM Counties"
Set db = CurrentDb
For i = 0 To Select_Counties2.ListCount - 1
If Select_Counties2.Selected(i) Then
strIN = strIN & Select_Counties2.Column(1, i) & ","
End If
Next i
strWhere = " WHERE County_GEOID in " & "(" & Left(strIN, Len(strIN) - 1) & ")"
strSQL = strSQL & strWhere
Debug.Print strSQL
'now the important bit:
db.CreateQueryDef ("User query results") 'create the query
Application.RefreshDatabaseWindow 'refresh database window so access knows it has a new query.
'query will now be visible in database window. make sure to delete the query between runs
'Access will throw an error otherwise
Set qdef = db.QueryDefs("User query results")
qdef.SQL = strSQL
qdef.Close
Set qdef = Nothing
Set db = Nothing
DoCmd.OpenQuery "User query results", acViewNormal
End Sub

Access VBA change Query criteria via VBA

I am trying to change the SQL statement of a query.
This is the following code:
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim sqlString As String
Set db = CurrentDb()
Set qdf = db.QueryDefs("Query1")
sqlString = "SELECT *all the Tables* FROM tab WHERE (((tab.columname)=*Variable*;"
qdf.SQL = sqlString
so my problem is the value of the Variable is not shown...
but it has to ge out of the string so I tried this:
sqlString = "SELECT *all the Tables* FROM tab WHERE (((tab.columname)= " & " *Variable*" & " ;"
I had to add "Variable" (quotation marks)
this then works half way.
it then uses the value of the variable it is set to but the quotes are missing...
The Goal of this Code is to change the Criteria that shows the data in the query.
The Variable value is as sample LA-85995561.
The way i want to change the value is via SQL statement.
I don't know further from here. thanks for any help!
(I am new to VBA)
Classic example to use parameterization, an industry best practice when using SQL at the application layer like VBA. And since you already use a querydef you can pass parameters easily withe PARAMETERS clause to define data type and placeholder.
SQL (save as a stored query)
PARAMETERS VariableParam Text(255);
SELECT * FROM tab WHERE tab.collumname = [VariableParam];
VBA
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim qdf As DAO.QueryDef
Dim sqlString As String
Set db = CurrentDb()
Set qdf = db.QueryDefs("mySavedQuery")
qdf!VariableParam = "LA-85995561"
Set rs = qdf.OpenRecordset()
' rs CAN BE USED IN FORMS/REPORTS RECORDSOURCES:
' Set Me.Form.Recordset = rst
' Set Me.Report.Recordset = rst
You could use PARAMETERS:
This passes a text string:
Sub Test()
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim rst As DAO.Recordset
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", "PARAMETERS MyNamedSearchValue TEXT; " & _
"SELECT * FROM MyTable WHERE columname = MyNamedSearchValue")
With qdf
.Parameters("MyNamedSearchValue") = "A"
Set rst = .OpenRecordset
End With
With rst
MsgBox .Fields("MyDateField")
.Close
End With
qdf.Close
End Sub
This passes a number:
Sub Test()
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim rst As DAO.Recordset
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", "PARAMETERS MyNamedSearchValue LONG; " & _
"SELECT * FROM MyTable WHERE columname = MyNamedSearchValue")
With qdf
.Parameters("MyNamedSearchValue") = 100
Set rst = .OpenRecordset
End With
With rst
MsgBox .Fields("MyDateField")
.Close
End With
qdf.Close
End Sub
You'll have to update the SQL to suit your needs. You could also pass it the name of a stored query rather than writing the SQL within the procedure.
If columname is text, then you can use something like this:
sqlString = "SELECT * FROM tab WHERE tab.columname='" & strVariable & "'"
For numeric data type:
sqlString = "SELECT * FROM tab WHERE tab.columname=" & str(lngVariable)
The Anser is that I had to use different marks:
WHERE (((tab.collumname)=""" & strVariable& """));"
it's about the """ & part it never made the " in the SQL thanks for all awnsers! brought me to my solution! <3

Vba Access error 91

I try to run this code
Public Sub Production_UpdateStatus(ByVal lngProductionId As Long, _
ByVal NewProductionStatus As eProductionStatus)
Dim oDb As DAO.Database
Dim oRst As DAO.Recordset
Dim StrSql As String
Dim strProductionStatus As String
On Error GoTo Err_Infos
GetCurrentProductionStatusString NewProductionStatus, strProductionStatus
Set oDb = CurrentDb
'Mise a jour du staut de production
StrSql = "UPDATE tProduction SET tProduction.Statut= '" & strProductionStatus & "'" _
& " WHERE (tProduction.IdProduction=" & lngProductionId & ");"
oDb.Execute StrSql
'Fermeture des connexions
oRst.Close
oDb.Close
Set oDb = Nothing
Set oRst = Nothing
Exit_currentSub:
Exit Sub
Err_Infos:
MsgBox "Erreur #" & Err.Number & " : " & Err.Description
Resume Exit_currentSub
End Sub
This code work but give me error 91.
Object variable or With block variable not set
It generate the following SQL query :
UPDATE tProduction SET tProduction.Statut= 'Nouvelle' WHERE (tProduction.IdProduction=2);
When I test direct query, I do not have any error. Could you help me to eliminate this error ?
Thanks
You are closing a recordset object, oRst, that was never initialized with Set. Because you run an action query you do not need a recordset and it may have lingered from prior code versions.
On that same note, because you are passing literal values to an SQL query, consider parameterizing with DAO QueryDef parameters that avoids concatenation and quote enclosures:
Dim oDb As DAO.Database, qdef As DAO.QueryDef
Dim StrSql As String, strProductionStatus As String
GetCurrentProductionStatusString NewProductionStatus, strProductionStatus
Set oDb = CurrentDb
StrSql = "PARAMETERS strProductionStatusParam Text(255), lngProductionIdParam Long;" _
& " UPDATE tProduction SET tProduction.Statut = [strProductionStatusParam]" _
& " WHERE (tProduction.IdProduction = [lngProductionIdParam]);"
Set qdef = oDb.CreateQueryDef("", StrSql)
qdef!strProductionStatusParam = strProductionStatus
qdef!lngProductionIdParam = lngProductionId
qdef.Execute dbFailOnError
Set qdef = Nothing
Set oDb = Nothing
Try to remove the oRst related code lines. This variable is not initialized and not used.

MS Access VBA QueryDef - With Block variable not set error

When using QueryDef i receive the following error "Object
variable or With block variable not set". when i copy the output of strSQL to a new Query it works fine. Please assist in the solution for this error.
The error occurs when running the following line;
Set qryDef = dbs.CreateQueryDef(strQueryName, strSQL)
See Entire code below
Private Sub ComboReclassify_AfterUpdate()
Dim dbs As Database
Dim strSQL As String
Dim strQueryName As String
Dim qryDef As QueryDef
strQueryName = "qryST_ReclassifyAttribute"
Dim attr As String
Dim ValueID As Integer
attr = [Forms]![frm_tblST_AttributesReclassification]![ComboItemAttributes]
ValueID = [Forms]![frm_tblST_AttributesReclassification]![ComboReclassify]
strSQL = "UPDATE dbo_tblST_DepartmentsAttributes SET " & (attr) & " = " & ValueID & " WHERE dbo_tblST_DepartmentsAttributes.id = 1"
Set qryDef = dbs.CreateQueryDef(strQueryName, strSQL)
DoCmd.OpenQuery "qryST_ReclassifyAttribute"
End Sub
You seemed to have missed setting the dbs object.
Private Sub ComboReclassify_AfterUpdate()
Dim dbs As Database
Dim strSQL As String
Dim strQueryName As String
Dim qryDef As QueryDef
strQueryName = "qryST_ReclassifyAttribute"
Dim attr As String
Dim ValueID As Integer
attr = [Forms]![frm_tblST_AttributesReclassification]![ComboItemAttributes]
ValueID = [Forms]![frm_tblST_AttributesReclassification]![ComboReclassify]
strSQL = "UPDATE dbo_tblST_DepartmentsAttributes SET " & (attr) & " = " & ValueID & " WHERE dbo_tblST_DepartmentsAttributes.id = 1"
'You have not set the dbs object. That is the problem
Set dbs = CurrentDB
Set qryDef = dbs.CreateQueryDef(strQueryName, strSQL)
DoCmd.OpenQuery "qryST_ReclassifyAttribute"
End Sub
Once you set it. It should work as normal !

How to save the result of a SQL query into a variable in VBA?

I want to execute a select statement and put the result of it (which is only 1 record with 1 value) in a variable.
This is in VBA code in access.
Private Sub Child_Click()
Dim Childnummer As Integer
Dim childnaam As String
Childnummer = Me.Keuzelijst21.Value
DoCmd.Close
DoCmd.OpenForm "submenurubrieken", acNormal, , " rubrieknummer = " & Childnummer & ""
childnaam = rubrieknaamSQL(Childnummer)
Forms!submenurubrieken.Tv_rubrieknaam.Value = childnaam
End Sub
Public Function rubrieknaamSQL(Child As Integer)
Dim rst As DAO.Recordset
Dim strSQL As String
strSQL = "SELECT rubrieknaam FROM dbo_tbl_rubriek where rubrieknummer = " & Child & ""
Set rst = CurrentDb.OpenRecordset(strSQL)
End Function
Simply have your Function return the value from the Recordset:
Public Function rubrieknaamSQL(Child As Integer)
Dim rst As DAO.Recordset
Dim strSQL As String
strSQL = "SELECT rubrieknaam FROM dbo_tbl_rubriek where rubrieknummer = " & Child & ""
Set rst = CurrentDb.OpenRecordset(strSQL)
' new code:
rubrieknaamSQL = rst!rubrieknaam
rst.Close
Set rst = Nothing
End Function
You can do this in pretty much one line by using the "DLookup" Function
rubrieknaam = Nz(DLookup("rubrieknaam ", "dbo_tbl_rubriek ", rubrieknummer & " =[Child]"), 0)
where Child is the ID of the record you are looking for.