我有一个用于数据输入的表单。我有一个列表框,其中包含所有产品的列表。我还有第二个列表框,包含所有公司。我有一个客户表,它有自己的名字和自动ID。我有一个产品列表,其中还包含名称和自动ID。我有第三张表,列出了客户拥有哪些产品。
示例:
tblCustomer
1 Company1
2 Company2
3 Company3
tblProducts
1 Product1
2 Product2
3 Product3
tblCustomerProducts
1 1 2 years
1 2 3 years
2 3 2 years
所以这意味着1是公司,1是产品,他们有2年
现在,当我进入表单时,我试图打开两个表的记录集并循环遍历它,然后当它找到匹配时,它会将相应的数字放在相应的文本框中。这就是我所拥有的
Private Sub Command15_Click()
Dim db As Database
Dim rst As Recordset 'Gets a variable ready to put a table into
Dim rst2 As Recordset 'Gets second variable ready to put a table into
Set db = CurrentDb()
Set rst = db.OpenRecordset("customer") 'Sets variable rst to the contents of the customer table
Set rst2 = db.OpenRecordset("product") 'Sets variable rst2 to the contents of the product table
Do While Not rst.EOF 'Loop through the customer table until it gets to the end of the file
If rst!["customer_name"] = lstCustomerName Then 'If the contents of the field customer_name is equal to that of the company highlighted on the form
txtCustomerFX.Value = rst!["id"] 'Then make the value of the the CustomerFX box equal to the ID associated with that company
rst.MoveNext
Loop
rst.Close
Do While Not rst2.EOF 'Loop through the product table until it gets to the end of the file
If rst2!["product_name"] = lstProductName Then 'If the contents of the field product_name is equal to that of the product highlighted on the form
txtProductFX.Value = rst2!["id"] 'Then make the value of the the ProductFX box equal to the ID associated with that product
rst.MoveNext
Loop
rst2.Close
End Sub
但它似乎并没有将数据放入文本框中。
答案 0 :(得分:1)
您无需深入了解记录集以匹配此类显示名称和ID。组合框或列表框可以绑定到隐藏的id列,只显示名称。用户看到名称,数据库看到数字。 启用控件向导(默认设置)后,尝试在联结表单上创建新的组合框。中选择:
tblCustomer
id
和customer_name
customer_name
这将设置组合框的属性以将ID存储在其值中,但只是向用户显示名称。您可以将此字段直接绑定到联结表上的客户字段,然后将代码(和按钮)全部消除。也重复产品!