vba访问2013表作为记录集并使用数据
问题描述:
我有一个用于数据输入的表单。我有一个列表框,其中包含所有产品的列表。我还有第二个包含所有公司的列表框。我有一个客户表,它有他们的名字和一个自动ID。我有一个产品列表,其中也包含一个名称和一个自动ID。我有第三张表列出了哪些客户拥有哪些产品。vba访问2013表作为记录集并使用数据
例子:
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
虽然它似乎并没有把数据放入文本框。
答
您不需要深入记录集就可以像这样匹配显示名称和id。组合框或列表框可以绑定到隐藏的ID列,只显示名称。用户看到名字,数据库看到数字。 打开控制向导(默认设置)时,尝试在联结表单上创建一个新的组合框。选择:
- 选择“我要组合框从另一个表或查询获取值”
- 选择
tblCustomer
- 添加
id
和customer_name
- 排序
customer_name
- 确保选中要隐藏密钥列被检查
- 选择标签
设置组合框的属性以将ID存储在其值中,但仅向用户显示名称。您可以将此字段直接绑定到联结表上的客户字段,然后一起删除代码(和按钮)。也重复产品!
请务必阅读选择标签时弹出的有用说明。 – Charles
您可能必须用End If终止您的If..Then块。 VB只允许排除它们,如果它在同一行上。 –
在你的if语句中使用正确的缩进,并用'End If'结束它。 – enderland