0
votes

I have a form "Form1" with a command button that when clicked, hides itself, and then opens another form "Form2" as follows:

Private Sub Command1_Click()
    Me.Visible = False
    DoCmd.OpenForm "Form2"
End Sub

The Form_Open subroutine of Form2 contains a check for errors. If an error is found, I want Form2 to display an error, close Form1, and then close itself:

Private Sub Form_Open(Cancel As Integer)
    AnError = 'check for an error
    If Not AnError Then
        'things are OK
     Else
        Response = MsgBox("There was an error in Form2.", 0, "Form2 error message")
        DoCmd.Close acForm, "Form1"
        DoCmd.Close
    End If
End Sub

I've tried numerous variations on this scheme for opening and closing the forms, and all fail in different ways. This particular one seems to do everything except actually close Form2 after the error message is displayed.

Once again I'm baffled about the way Access 2010 VBA handles the opening and closing of forms; the reference information at MSDN is atrocious. Thanks for any help.

3
Your code looks reasonable. Have you verified that the code not only reaches DoCmd.Close but also does not throw an error on that line?Mark Balhoff

3 Answers

2
votes

You are close. - this code will also close Form2:

Private Sub Form_Open(Cancel As Integer)
'AnError = 'check for an error
    If Not True Then
        'things are OK
    Else
        Response = MsgBox("There was an error in Form2.", 0, "Form2 error message")
        DoCmd.Close acForm, "Form1"
        DoCmd.Close acForm, Me.Name 'Me.Name is used for illustration purposes, you can  also use "Form2" 
    End If
End Sub
0
votes

I've always seen this done via the UnLoad keyword

Try this,

If Not AnError Then
        'things are OK
     Else
        Response = MsgBox("There was an error in Form2.", 0, "Form2 error message")
        Unload Form1
        'Unload Me
        'OR since you can cancel this form loading
        Cancel = True
    End If
0
votes

Try changing to the Me object:

Private Sub Form_Open(Cancel As Integer)
    AnError = 'check for an error
    If Not AnError Then
        'things are OK
     Else
        Response = MsgBox("There was an error in Form2.", 0, "Form2 error message")
        DoCmd.Close acForm, "Form1"
        Me.Close
        ' or possibly Unload Me
    End If
End Sub