我有一个带有CustID的查询,它与CustID有关联的多个业务。我不能使用Dlookup,因为它只返回一个变量。我想在一张表格上显示,对于这个custID,这里是它附属的所有业务。我希望企业在表单上的另一个表格中出现在一个字段(业务)中。
我从这个开始
Public Sub OpenRecordset()
Dim db As Database
Dim rs As Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("Q:businesses")
Do While Not rs.EOF
T:Custinfo!business = NAME (I am lost in between on how to identify the custid and place the businesses into the table field as a Dlookup)
rs.movenext
Loop
rs.Close
Set rs = Nothing
db.Close
End Sub我一直在查看其他示例,但似乎无法将查找替换发生在哪里,您将如何将其作为数据表放在表单上呢?
发布于 2015-03-12 21:23:59
你不需要DLookup。你可以做两件事之一:
1)使用列表框,并设置与查询相等的记录源(假设q:业务已被适当定义以作为结果提供给企业)
2)仍然需要您的查询是适当的,但是您可以创建一个包含其中所有业务的字符串:
Public Sub OpenRecordset()
Dim db As Database
Dim rs As Recordset
Dim StrBusinesses As String
Set db = CurrentDb
Set rs = db.OpenRecordset("qryBusinesses")
If rs.EOF and rs.BOF Then
MsgBox("No businesses exist for this Customer")
Exit Sub 'Or do whatever else you want if there are no matches
Else
rs.MoveFirst
End If
StrBusinesses = ""
Do While Not rs.EOF
StrBusinesses = StrBusinesses & rs!Business & ", "
rs.movenext
Loop
rs.Close
StrBusinesses = Left(StrBusinesses, Len(StrBusinesses) - 2)
Forms!MyForm.MyField = StrBusinesses 'Set the field equal to the string here
Set rs = Nothing
db.Close
End Sub当然,这假定查询"Q:Business“的定义是为了获得适当的信息,如:
SELECT custID, business FROM tblBusinesses WHERE custID = X其中"X“是您正在寻找的custID。
如果需要动态设置查询,则需要设置querydef。
编辑以包括querydef代码*
要设置querydef,将其放在代码的开头:
Dim qdf As QueryDef
Set qdf = CurrentDb.QueryDefs("qryBusinesses")
qdf.SQL = "SELECT custID, business FROM tblBusinesses" _
& " WHERE custID = " & Forms!MyForm.CustID 'replace with actual form and field这假设i) qryBusinesses已经存在,2) custID是一个数字字段
编辑*如果您定义查询以查看表单本身,则不需要将sql设置为: qdf.sql = "SELECT custID,“_&”custID = Forms!MyForm.CustID“。
这样就不需要重新定义sql了。但是,将custID放入qdf本身会更加动态,因为调试任何问题都更容易,因为您可以看到原始方法中正在运行的确切的sql。
https://stackoverflow.com/questions/29018982
复制相似问题