RecordSet和Ms Access 2007

时间:2015-03-12 19:49:07

标签: vba ms-access access-vba ms-access-2007

我的查询具有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

我一直在查看其他示例,但似乎无法将dlookup替换发生在哪里以及如何将其作为数据表放在表单上?

1 个答案:

答案 0 :(得分:0)

您不需要DLookup。你可以做以下两件事之一:

1)使用列表框并将recordsource设置为等于您的查询(假设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代码*********************** 还在上面和下面的代码中将查询的名称更改为“qryBusinesses”,因为我不确定您是否可以使用冒号进行查询。

要设置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已经存在,                   ii)custID是一个数字字段

EDIT ************** 如果定义查询以查看表单本身,则不需要设置sql,因此如果查询(在VBA中或通过查询向导)定义为:     qdf.sql =“SELECT custID,business FROM tblBusinesses”_          &安培; “WHERE custID = Forms!MyForm.CustID”

然后你不需要重新定义sql。但是,将custID放入qdf本身会更加动态,因为它可以更容易地调试任何问题,因为您可以看到在原始方法中运行的确切sql。