Scenario: I am creating an advanced search form for an access database. They alre开发者_StackOverflowady have single search forms that run access queries and open in the query window.
Problem: I'd like to mimic this functionality but I am looking to create the query as a string within the code and then open it in a query window. Is this possible? I have searched google but didnt find anything. If its not possible are there any alternatives?
Thanks in advance.
You can open a Form in datasheet view which looks like a query window but you need to create a form add the controls to it and then set the recordsource
e.g.
Dim rst As DAO.Recordset
Dim rsField As DAO.Field
Dim control As Access.TextBox
Dim frm As Form
Set frm = CreateForm()
frm.Visible = False
Dim sql As String
sql = "Select * from MSysObjects"
Set rst = CurrentDb.OpenRecordset(sql)
For Each rsField In rst.Fields
Debug.Print rsField.Name
Set control = CreateControl(frm.Name, acTextBox, acDetail)
With control
.Width = 100
.Height = 100
.Top = 100
.Left = 100
.ControlSource = rsField.Name
.Name = rsField.Name
End With
Next rsField
Set rst = Nothing
frm.Visible = True
frm.RecordSource = sql
DoCmd.OpenForm frm.Name, acFormDS
There are a couple of problems with this.
- It creates a new form each time. This means when a user closes the form they'll be asked if they want to save it. So you might want to investigate opening an existing form and modifying (clearing existing items)
- The query is executed twice. the first time to get the fields and the second to actually show the form. Depending on what the query does this may or may not be an issue.
Honestly modifying a querydef is probably the saner way to go.
精彩评论