简体   繁体   中英

MS Access - Form and subform based on same table, but different record

I have an Access database based on linked tables from SQL Server (ODBC). The main form is based on a SQL Server Table with a primary key field called PRJ_ID . Every record has an integer field called MASTER_PRJ_REF which can contain the PRJ_ID of the same record or another record of the same table.

Basically, i can have a "master" record and several "slave" records within the same table. I also specify that in SQL Server i created a one-to-many relationship between the two fields.

I want to use a subform to display and eventually modify some fields of the "master" record, but with the parent form displaying the "slave" record. What i did is creating the subform with this relation:

Parent form: PRJ_ID
Sub form: MASTER_PRJ_REF

Problem is, the subform displays the same record of the parent form, not the referenced one. So, it seems that it is not following my relationship, but is following the PRJ_ID to PRJ_ID relationship.

Why is the relationship not working?

Is it correct to make a relationship between two fields of the same table?

I don't know exactly why Access mess up as I am always doing things myself with VBA and pure SQL and never rely on Access built-in functionalities, which is generally more efficient, and avoid the "bugs" like the one you encounter.

So if you want to code like me, here's a workaround I can propose.

Start to remove the parent/child (master/slave if you prefer) relations on your form.

In the current event of your main form, add this code :

dim strSQL as string

' adapt the following SQL where needed :
' - adapt table name
' - Replace * with the columns you need
' - surround the MASTER_PRJ_REF with quotes if it's not a INT

strSQL = "SELECT * FROM thetable WHERE PRJ_ID=" & me!MASTER_PRJ_REF

' That's the tricky part. 
' I assumed your subform is named SubForm1, adapt this.
' You should assign your SQL to your subform record source 
' But access doesn't always accept all syntax following the context,
' so choose one that work for you and remove the others.

SubForm1.RecordSource = strSQL
Form_SubForm1.RecordSource = strSQL ' ---> this one should work for sure if you have added any code to the subform (create the subform module, even if its empty.
Forms("SubForm1").RecordSource = strSQL
Me!SubForm1.Form.RecordSource = strSQL
Forms!NameOfMainForm.SubForm1.Form.RecordSource = strSQL

Hopefully one of the 5 solution should work.

If the data is not updated right away, add the following, with the same syntax as the one of the 5 you picked and that worked.

 SubForm1.Requery

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM