user3268289
user3268289

Reputation: 185

Access 2010 VBA: Why doesn't this sequence of form openings and closings work?

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.

Upvotes: 0

Views: 347

Answers (3)

ron tornambe
ron tornambe

Reputation: 10780

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

Upvotes: 2

Johnny Bones
Johnny Bones

Reputation: 8402

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

Upvotes: 0

Jimmy Smith
Jimmy Smith

Reputation: 2451

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

Upvotes: 0

Related Questions