Create a query dynamically
Asked Answered
B

3

20

Hi I need to create a query in MSAccess 2003 through code (a.k.a. VB) -- how can I accomplish this?

Briquette answered 23/12, 2008 at 23:47 Comment(0)
R
39

A vague answer for a vague question :)

strSQL="SELECT * FROM tblT WHERE ID =" & Forms!Form1!txtID 

Set qdf=CurrentDB.CreateQueryDef("NewQuery",strSQL)
DoCmd.OpenQuery qdf.Name
Reprise answered 23/12, 2008 at 23:56 Comment(1)
Ugh I've been trying things similar to this for the past 3 hours :( Thanks a bunchBriquette
W
8

Thanks for this answer and the small piece of code. If somebody needs to define the datatypes for the variables used, use this:

    Dim strsql As Variant
    Dim qdf As QueryDef
Windywindzer answered 23/1, 2014 at 10:48 Comment(0)
A
8
Dim strSql As String 'as already in example
Dim qdf As QueryDef 'as already in example

strSql = "SELECT * FROM tblT WHERE ID =" & Forms!Form1!txtID 'as already in example

On Error Resume Next
'Delete the query if it already exists
DoCmd.DeleteObject acQuery, "NewQuery"

Set qdf = CurrentDb.CreateQueryDef("NewQuery", strSql) 'as already in example
DoCmd.OpenQuery qdf.Name 'as already in example

'release memory
qdf.Close 'i changed qdef to qdf here and below
Set qdf = Nothing
Aitch answered 11/7, 2017 at 12:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.