This post is a result of a question I had from a visitor.
They were having an issue opening a related form when there was not a related record.
One way of solving this issue is using the default value on the sub form.
2 different ways to handle a main form and sub form are having the main information on the top of the form and the sub information in a datasheet on the lower part of the form, linked to the main (parent) record on the top. Or, we can open the sub form on a click event, to the record related to the form we just clicked on.
Here is our main table information:
Here is our related, “sub”, table information:
When I create 2 simple forms (a form and subform), and add a “click” action to my button, I get this:
Here is the code for my “click” event:
Private Sub btnPatientDetail_Click() DoCmd.OpenForm "frmPatientSub", , , "StudyID=" & Me.StudyID End Sub
This works great on records with “children”, (Records: 14, 15, 16), in tblSub.
But, when we click on StudyID 17 or 23 we get a 0!
So in order to fix this, we’ll add a default value to the “frmPatientSub” form’s StudyID text box
Now when we click on a record that has no related records, like 17 or 23, we’ll get this:
We’re not actually adding the record to the table, we are “about to”, we are just defaulting the field to the “StudyID”, so we are ready to add a new record, but if we want to close the form, we are good, and no record will be added.
Do you have any questions or comments? Leave them below, or send me a comment.
Learn Access VBA: Understand Tables, Queries, Forms, and Reports
Learn Access VBA: From Zero to Database Hero If you’ve ever opened Microsoft Access and wondered how all the pieces fit together — tables, queries, forms, and reports — this tutorial is made for you. In just a few minutes, you’ll understand how Access works behind the scenes and see how VBA (Visual Basic for […]
How To Make An Access Form Time Picker
Here is a relatively easy way to select times for your time entry text boxes. It’s a reusable form that allows you to pick a time from an Access form. There are probably different ways to do this but here is the way I would do it. On the form that has the time fields, […]
How to pick a file to load In VBA
How to Pick a File in VBA: FileDialog & GetOpenFilename Explained When building Excel VBA applications, you’ll often need to let users pick a file to load in VBA. Instead of hard-coding file paths, you can use built-in dialogs that make file selection easy and user-friendly. VBA offers two main approaches: FileDialog object (flexible, customizable) […]
What is the purpose of the Me keyword in Access VBA?
What does the Me keyword mean? “Me” refers to the Access form currently in focus. Instead of writing out the entire form reference, you can just use the keyword “Me” which is easier. Like: Me.txtbox = “I am a textbox on the form that currently has the focus.” or you can update a label’s caption […]
Support these sponsors: