Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Yes there is!</p> <p>Obviously, you need to be able to relate the combo box selection to the value you wish to be populated into the other field(s). Assuming that you have a 1:1 relationship with the PK (since you want to display only one value in your form), you can use the AfterUpdate event plus the DLookup() function to retrieve a related value using the PK.</p> <p>As a simple example, I set up a table named Foods as follows:</p> <blockquote> <p>FoodID, FoodName, FoodCategory</p> <p>1, Orange, Fruits</p> <p>2, Chicken, Poultry</p> <p>3, Almond, Nuts</p> <p>4, Lettuce, Vegetables</p> </blockquote> <p>In the form, I have a control that selects the FoodID as the PK bound value named ComboFoods, and an unbound text box control named TextFoodCategory that we will populate with the FoodCategory from the Foods table.</p> <p>I've assigned the following code to the AfterUpdate event of the Combo Box so that when the value of the combo box changes, the text box will be populated:</p> <blockquote> <p>Private Sub ComboFoods_AfterUpdate()</p> <p>'Create a variable to store the combo box primary key selection</p> <p>Dim VarComboKey As Integer</p> <p>'Create a variable to store the DLookup results</p> <p>Dim VarFoodCat As Variant</p> <p>'Capture the primary key of the combo box</p> <p>VarComboKey = Me.ComboFoods.Value</p> <p>'Retrieve the related field value</p> <p>VarFoodCat = DLookup("[FoodCategory]", "[Foods]", "[FoodID] = " &amp; VarComboKey)</p> <p>'Set the value of the text box to the variable</p> <p>Me.TextFoodCategory.Value = VarFoodCat</p> </blockquote> <p>This will return the FoodCategory that is related to PK. This is all using one table, but the DLookup statement can be modified to reference any query or table that contains the PK.</p> <p>Please note that DLookup will only work properly when the PK is unique in the data you are referencing. It will not work in a one to many relationship unless you specify other criteria that restrict the results to one record. There are other ways to use SQL queries and recordsets within VBA if you need to return multiple records, but that this out of scope for this question.</p> <p>This worked when tested - best of luck! </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload