Search code examples
vbams-accessms-access-2007

Add VBA code to MS Access userform using VBA


I have a script that automatically generates a form. This form is only temporary and can be deleted after closing. To prevent having to do it manually, I'd like to add a button or a form_close() method in which there should be some code to delete the form (if this is possible at all).

Otherwise, I'd like to be able to prevent te pop-up forcing me to save the form and give it a name once I close it (shown below in Dutch).

'save form' pop-up (in Dutch)

I haven't been able to either disable this pop-up, or add VBA code using VBA code. Can anyone tell me wether this possible and maybe give an example?


Solution

  • You don't need VBA code in the form to do this, just call a public function from the OnClick event of the button.

    ' This is called from the "Close" button on the temp form
    Public Function CloseWithoutSave(fName As String)
        DoCmd.Close acForm, fName, acSaveNo
    End Function
    
    ' Demo
    Public Sub CreateTestForm()
    
        Dim F As Form
        Dim btn As CommandButton
    
        Set F = Application.CreateForm()
        F.Caption = "This is a test form!"
    
        Set btn = CreateControl(F.Name, acCommandButton, Left:=100, Top:=100)
        btn.Caption = "Close me"
        btn.OnClick = "=CloseWithoutSave(""" & F.Name & """)"
    
        ' Open test form in form view
        DoCmd.Restore
        DoCmd.OpenForm F.Name, acNormal
    
    End Sub