Dynamic Query using VBA

jbroge

New member
Local time
Today, 09:10
Joined
Aug 6, 2015
Messages
5
Hello all,

I am attempting to create a dynamic query based on form driven criteria using VBA. I found a few tutorials out there, but I'm receiving an error saying

Run-time error '13':
Type mismatch.

Here is the code I am using
Code:
Private Sub cmd_RunQuery_Click()

Dim strsql As Variant
Dim qbf As QueryDef

strsql = "SELECT * FROM WorkOrderLogAll WHERE RetestLocation =" & "'" & Forms!CustomerRetestDatabaseSearch!RetestLocation & "'" And CustomerName = " & " '" & Forms!CustomerRetestDatabaseSearch!CustomerName & "'"

Set qbf = CurrentDb.CreateQueryDef("DynamicQuery", strsql)
DoCmd.OpenQuery qbf.Name


Set qdf = Nothing
Set db = Nothing


End Sub
When I try to run using just one criteria "RetestLocation" or "CustomerName", it returns results. Its only when I try to use two or more criteria I get the error.

Both fields are Short Text Data Types in the table. The form uses drop boxes for both fields.

Any help would be appreciated!
 
Let me help you help yourself:

What's strsql resolve to?
 
Without details I have to guess RetestLocation is a number field and you are passing value as string since you are using &'&.
 
Sample code segment to create a Select Query through VBA.
Code:
dim db as database
dim qrydef as Querydef
dim strSql as string

strSql = "Select Table1.* From Table1;"
set db = currentdb
set qrydef =db.CreateQueryDefs("Query1")
qrydef.SQL = strSql
db.Querydefs.Append qrydef
db.Querydefs.Refresh

This is a SELECT Query. You cannot run it using DoCmd.OpenQuery command. Action queries are (Append, Delete, Update etc.) run with DoCmd.
Code:
Set rst = db.OpenRecordset("Query1")
is the statement used to open the Query and to process the record in it.
 
Last edited:
The following statement is also valid.
Code:
set rst = db.OpenRecordset(strSql)
You don't need to create Query1.
 
Thanks [FONT=&quot]apr pillai. I apologize for my ignorance but this is all new to me, and what better way to learn than to ask questions.[/FONT]
 

Users who are viewing this thread

Back
Top Bottom