Add bound fields to form using CreateControl

Q

quackerbacker

I am trying to figure out the VBA code to add all of the fields in a forms
recordset.

Code execution stops at frm.Recordset.Fields.Count. The errors state that
"The expression you entered refers to an object that is closed or doesn't
exist"

This error occurs when I open the form in design view. When I open the form
as acNormal, the Recordset object is available but you cant add controls in
normal view.

Dim frm as Access.Form
Dim ctl as Control

DoCmd.OpenForm strFormName, acDesign

Set frm = Forms(strFormName)
'
'Add all fields to detail portion of form
For intCounter = 0 To frm.Recordset.Fields.Count - 1
Set ctl = CreateControl(frm.Name, acTextBox, acDetail, ,
frm.Recordset.Fields(intCounter).Name)
Set ctl = Nothing
Next

Any help would be appreciated.
 
A

Allen Browne

That's correct: the recordset is not created in design view.

You could get at it through the form's RecordSource:
Dim rs As DAO.Recordset
Dim strSql As String
strSql = Forms(strFormName).RecordSource
Set rs = dbEngine(0)(0).OpenRecordset(strSql, dbOpenDynaset)

In general, this approach is only useful for writing wizard-type things, not
for end-user apps. For example, if you plan to open things in design view,
you won't be able to create an MDE.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top