Conrad Addo
Conrad Addo

Reputation: 434

Run vba code on Form_Load of new form but only if previous form has a specific name

I would like to have a button to open a form and then run VBA code on that form. So either using Form_Load or and intermediate module. Does anyone know how to do this?

Thanks

Upvotes: 0

Views: 843

Answers (3)

John Bingham
John Bingham

Reputation: 2006

Lets say the new form be opened from a number of forms in your application;

Can more than one of the calling forms be open at any one time?

If not, use this:

Private Sub Form_Load()
    If isLoaded("Form1") then
        Form1_InstructionSet
    ElseIf isLoaded("Form2") then
        Form2_InstructionSet
    ...
    End If
End Sub

Private Sub Form1_InstructionSet
    ...
End Sub

etc.

If more than one of the calling forms can be open simultaneously, you should parameterise the new form, as per @Andre's answer above.

Upvotes: 0

Tieme Woldman
Tieme Woldman

Reputation: 67

Declare a module level variable in the second form:

Dim Prev As Form

In the On Load-event of the second form (this sets a reference to the first form):

Set Prev = Screen.ActiveForm

And in the On Close-event:

Set Prev = nothing

Now you can check the name of the previous form with:

If Prev.Name = "..." Then
    ... your actions
End If

Furthermore you can check any property or field from the first/previous form this way. Prev is acting like Me now.

Upvotes: 2

Andre
Andre

Reputation: 27644

Use OpenArgs.

First form:

DoCmd.OpenForm "SecondForm", OpenArgs:=Me.Name

Second form:

Private Sub Form_Load()

    If Me.OpenArgs = "FirstForm" Then
        ' Stuff
    End If

End Sub

Upvotes: 3

Related Questions