I have a question regarding the code below which creates a new query based on combobox selections or a textbox entry on an Access form.
Sometimes when I run the que
The runtime errors might be fixed by adding DB.QueryDefs.Refresh
after adding or deleting a querydef.
Dim DB As Database
Set DB = CurrentDb
DB.QueryDefs.Delete "NewQuery"
DB.QueryDefs.Refresh
Set qdf = DB.CreateQueryDef("NewQuery", sqlquery)
DB.QueryDefs.Refresh
DoCmd.OpenQuery "NewQuery"
There are some other problems with your code.
You should give your form controls meaningful names instead of e.g. ComboBox4
. This will help readability a lot.
Your construction of ComboBox_condition
is overly complex. The most elegant solution to avoid all these doubled conditions is:
Always add them with AND
, including the first one:
If ComboBox0 <> "" Then
ComboBox_condition = ComboBox_condition + " AND TABLE.PayGroupRegionCode = '" & ComboBox0 & "'"
End If
' ...
If ComboBox12 <> "" Then
ComboBox_condition = ComboBox_condition + " AND TABLE.JobCode = '" & ComboBox12 & "'"
End If
' ...
and then when you build the final statement, add a dummy WHERE condition that is always True, so the WHERE clause is always valid:
sqlquery = "SELECT * FROM TABLE WHERE 1=1 " & ComboBox_condition
Even the check If ComboBox_condition <> ""
can be omitted.