The data structure behind a form/subform usually consists of 2 tables:
a) the main form's table, with a primary key field;
b) the subform's table, with a foreign key field to the main form's table.
Since the subform's table relates to the primary key of the main form's
table, the first thing you need to do is discover what the foreign key
value is for the record you want to match. You can then find that record
in the main form. At that point Access loads all the related records in
the subform, so you can then find the record you want in the subform.
The example below works with the Customer Orders form in Northwind. This
form is bound to the Customers table, with Orders for the customer in the
subform. If you add an unbound text box to the main form to enter the
order number you want to see, it has to lookup which customer this is for,
locate that record in the main form, and then choose the right order in
the subform. The code assumed you added a text box named txtFindOrder to
the main form (and set the form's AllowEdits property to Yes so you can
enter a number to find):
Private Sub txtFindOrder_AfterUpdate()
Dim rs As DAO.Recordset
Dim strWhere As String
Dim varResult As Variant
If Not IsNull(Me.txtFindOrder) Then
If Me.Dirty Then 'Save first
Me.Dirty = False
End If
'Lookup the customer for this order.
strWhere = "OrderID = " & Me.txtFindOrder
varResult = DLookup("CustomerID", "Orders", strWhere)
If IsNull(varResult) Then
MsgBox "No such order."
Else
'Find the record in the main form.
strWhere = "CustomerID = """ & varResult & """"
Set rs = Me.RecordsetClone
rs.FindFirst strWhere
If rs.NoMatch Then
MsgBox "Customer not found. Is form filtered?"
Else
Me.Bookmark = rs.Bookmark
Set rs = Nothing
'Now find in the subform.
strWhere = "OrderID = " & Me.txtFindOrder
With Me.[Customer Orders Subform1].Form
Set rs = .RecordsetClone
rs.FindFirst strWhere
If rs.NoMatch Then
MsgBox "Not found in subform"
Else
.Bookmark = rs.Bookmark
End If
End With
End If
End If
End If
Set rs = Nothing
End Sub
--
Allen Browne - Microsoft MVP. Perth, Western Australia.
Reply to group, rather than allenbrowne at mvps dot org.
Robert said:
We recently changed a database to using subform.
After the change, when end user attempts to search a record in the
subform, as it only shows those records related to that in main form, he
is not successfully to search as before. That is fully understandable.
However, he would like to find the record even though by searching a
certain field in the subform so that both record in main form and subform
changes (according to the record searched in the subform).
Is there any way to do so OR just tell him that it is not possible ?
Your advice is sought.
Thanks