How to Create a New Form Programmatically in VBA Using an Existing Form as a Template in MS Access

Public Sub CreateNewForm()
' Purpose: This Sub creates a new MS Access Form using another form as a template
Dim frm As Form, frmNameJustCreated As String, frmNameFinal As String
 
 ' Create a form based on another form called frmBlankForm
 Set frm = CreateForm(, "frmBlankForm")
 frmNameJustCreated = frm.Name ' This would be something like Form1, Form2, Form3 etc.
 frmNameFinal = "frm" & frm.Name ' Prefix "frm" to make Form naming convention consistent
     

 If formExistsInTheDatabase(frmNameFinal) Then
    MsgBox frmNameFinal & " already exists in the database" ' Just to check
    'DoCmd.DeleteObject acForm, frmNameJustCreated
 Else
    'MsgBox frmNameJustCreated
    With frm
        .RecordSource = "contacts" ' Set the record source of the newly created form to table called "contacts"
        .Section(0).Height = 400 ' set the height of the Form Detail to 400 twips (that's too short)
        .Section(acformHeader).Height = 400 ' Form Header
        .Section(acformHeader).Visible = True  ' Form Header
        .Section(acformHeader).DisplayWhen = 0  ' Form Header
        '.Section(2).Height = 100 ' Form Footer
        
    End With
    
    DoCmd.Save acForm, frmNameJustCreated ' Save the form as Form1, Form2, Form3 etc.
    DoCmd.Close acForm, frmNameJustCreated ' Close the form
    DoCmd.Restore
    DoCmd.Rename frmNameFinal, acForm, frmNameJustCreated ' Rename the form from Form1 to frmForm1
 End If
 
End Sub

This article was written by Bashir Ahmed. Code in this article drives the operation of MAARS (MS Access Application wRiting Software). MAARS is an intelligent automation program that speeds up MS Access Application Development by 10x, 20x or 100x times. To learn more about MAARS, click here.

Disclaimer:

Some information included in this article may have been sourced from other publicly available websites and blogs. In such cases, credit goes to those authors for the original ideas and thoughts, but we do take credit for putting valuable information together and improve the efficiency of other office developers.