Hristo Dobrev
Hristo Dobrev

Reputation: 107

Pass parameters from one form to another and add new records

I want:

To be able to open a form, select an item from a control box, click a button to open a new form and be able to input new records that have the previously selected item added to their fields.

What I have done so far:

I have made two forms, added the controls in both, added a command button. I have used MS Access wizard to add this code:

Private Sub CommandNext_Click()
  On Error GoTo Err_CommandNext_Click

    Dim stDocName As String
    Dim stLinkCriteria As String

    stDocName = "FormX"
    DoCmd.OpenForm stDocName, , , "[BatchID] = " & Me![ListBatch], acFormAdd

  Exit_CommandNext_Click:

    Exit Sub

  Err_CommandNext_Click:

    MsgBox Err.Description
    Resume Exit_CommandNext_Click

End Sub

The third line is mine.

As a result:

In both cases in the second form the Filter property gets populated with the parameter I've sent using the button, but that isn't what I am aiming for.

Upvotes: 0

Views: 6422

Answers (1)

Mark3308
Mark3308

Reputation: 1333

Are you aware the 4th argument for the open form command is the where condition or filter to apply?

If you use the last parameter which is called open arguments (OpenArgs) then you can write code in the 2nd forms open event to set the default value for the column in question.

The open form code would look something like this:

DoCmd.OpenForm stDocName, , , , acFormAdd, , Me![ListBatch]

You could then put code similar to the following in this 2nd forms open event:

Dim defaultID as Long
defaultID = CLng(Nz(Me.OpenArgs, 0))
If defaultID = 0 Or IsNull(Me.OpenArgs) Then
    Cancel = True
    Exit Sub
End If
Me.TextBoxBatchID.DefaultValue = defaultID

Or if you do not need the ID to be set for every new record you could just set the current value of the control to the defaultID variable.

 Me.TextBoxBatchID = defaultID

Please note the code above would not open the form if the open argument turned out to be empty or 0.

Upvotes: 2

Related Questions