Question

I have a subform bound to a SQL statement. Inside the subform, I have a few text boxes bound to the fields of this SQL. However, I have another text box that needs to be bound to a field from a different SQL statement with criteria from the first one. My code looks like below:

Dim subform As Object
Dim formFilter As String

formFilter = "SELECT * FROM my_table_1"
Set subform = Me!my_subform.Form    
subform.RecordSource = formFilter

subform.field1.ControlSource = "tb1f1"
subform.field2.ControlSource = "tb1f2"
...
subform.f3.ControlSource = "= SELECT TOP 1 tb2f3 FROM my_table_2 WHERE tb2f1 = '" & [tb1f1] & "' AND tb2f2 = '" & [tb1f2] "' ORDER BY tb2f4"

I cannot use a DLOOKUP function here directly, because I need to sort the table result.

Thanks in advance for your help.

Was it helpful?

Solution

I think I would simply create a little function to go get the result you want. It would probably be best to simply rework DLookup in your own function and add sort but I won't do that here.
First the form code. Notice I am not setting the recordsource, just the value which may not be what you want.

subform.f3 = fGet_tb2f3([tb1f1], [tb1f2])

Then the function code (put in your own error handling)

Public Function fGet_tb2f3(tblf1 as String,tblf2 as String) as String  
    Dim rst as dao.recordset
    Dim db as database
    set db = currentdb
    set rst = db.openrecordset("SELECT TOP 1 tb2f3 FROM my_table_2 WHERE tb2f1 = '" & tb1f1 & "' AND tb2f2 = '" & tb1f2 "' ORDER BY tb2f4",dbopensnapshot
    if not rst is nothing then
        if not rst.eof then fGet_tb2f3 = rst!tb2f3
        rst.close
        set rst = nothing
    end if
    db.close
    set db = nothing
end Function

OTHER TIPS

You can't bind controls on the same form to 2 different recordsets. The only thing you could do is pull data from 2 different recordsets, but that's probably not the best way to do anything.

In order to do that, you'd have to create a second recordset and grab that value in it. Something like:

Dim db as Database
Dim rec as Recordset

Set db = CurrentDB
Set rec = db.OpenRecordset("SELECT TOP 1 tb2f3 FROM my_table_2 WHERE tb2f1 = '" & [tb1f1] & "' AND tb2f2 = '" & [tb1f2] "' ORDER BY tb2f4")

Me.MyControlName = rec(0)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top