Link field on form1 to field on form2

algiersnola

New member
Local time
Today, 09:48
Joined
Nov 4, 2009
Messages
5
I have 2 forms, both are related. The first form has a field for the primary key (autonumber). When i click on a button on the first form to open the second form I want the number from the primary key on the first form to be automaticaly inserted into a field on the second form, which is the foreign key in the second form. That way I don't need to remember the number and manually insert it in the second form. Hope this makes sense.
 
I have 2 forms, both are related. The first form has a field for the primary key (autonumber). When i click on a button on the first form to open the second form I want the number from the primary key on the first form to be automaticaly inserted into a field on the second form, which is the foreign key in the second form. That way I don't need to remember the number and manually insert it in the second form. Hope this makes sense.

Have a look at the openargs method in help - should do the trick
 
Your code using OpenArgs would be something like this.

In the first form:

Code:
Private Sub OpenSecondForm_Click()
 If Me.Dirty Then Me.Dirty = False
 DoCmd.OpenForm "SecondFormName", , , , , , Me.AutoNumberFieldName
End Sub
In the second form:
Code:
Private Sub Form_Load()
  DoCmd.GoToRecord , , acNewRec
  If Len(Nz(Me.OpenArgs, "")) > 0 Then
   Me.ForeignKeyFieldName = Me.OpenArgs
  End If
End Sub
If you will sometimes want to open the second form independently and not want to go to a new record at this time, you can move the command to go to a new record inside of the If...Then...End If construct, like this:
Code:
Private Sub Form_Load()
  If Len(Nz(Me.OpenArgs, "")) > 0 Then
    DoCmd.GoToRecord , , acNewRec
    Me.ForeignKeyFieldName = Me.OpenArgs
  End If
End Sub

Remember that the Datatype of the Foreign Key Field has to be an Integer or Long, depending on how big the number can be. It cannot be defined as an AutoNumber.
 

Users who are viewing this thread

Back
Top Bottom