Reputation: 109
Still learning, apologies in advance.
I have two tables Parenttbl and Childtbl, linked in a one to many relationship.
I have a ParentForm and a ChildForm. I would like a button on my ParentForm that opens ChildForm with a new record, where the foreign key is automatically populated, but cannot for the life of me do this.
I have played around with the Macro Editor. With OpenForm I can create a new record, but the foreign key is blank.
I have tried to follow the instructions here and here, but could not get it to work.
Thanks in advance.
Upvotes: 1
Views: 1670
Reputation: 49049
As noted, if you drop the 2nd child form into the main form, then no add button is required, and you can even edit all the past/existing records.
However, if you really want two separate forms?
The the button code to launch the 2nd form can be this:
if me.dirty = true then me.dirty = false ' save our data in form
docmd.OpenForm "MyChildForm",,,,acFormAdd
forms("MyChildForm")!MyFKColumnName = me!id
So the above will launch the form to a new new blank reocrd, and then we set the column used to relate back to the main form. Of course you replace !MyFKColumn with the actual name of the column used in this relationship. And same goes for the often used "ID", so repalce "ID" in me!ID with the name of your PK column in the main form.
Upvotes: 1
Reputation: 55841
If you have set up the subform control and its properties LinkMasterFields and LinkChildFields, the FK will be filled in automatically. Zero code is needed.
Upvotes: 1