我有一个访问表单,该表单使用SQL Server作为数据源。我想为用户提供使用表单ID号过滤表单的选项。我已经创建了捕获ID号的控件,并且正在使用下面的代码来获取数据。
Dim strReq As String
strReq = Me.txtSearchTerm
StrSql = "SELECT tblOrders.*, tblFleetVendors.* FROM tblOrders"
StrSql = StrSql + "INNER JOIN tblFleetVendors ON tblOrders.VendorId = tblFleetVendors.VendorID"
StrSql = StrSql + "WHERE tblOrders.VendorId<>774 'AND tblOrders.OrderID =" & strReq & "));"
Set db = CurrentDb()
Set qdf = db.QueryDefs("qryOrders")
qdf.SQL = StrSql
Set rst = db.OpenRecordset("qryOrders", dbOpenDynaset, dbSeeChanges)
intRecords = rst.RecordCount
If intRecords <= 0 Then
MsgBox "There are no records that match your search"
rst.Close
Set rst = Nothing
Set db = Nothing
rst.Close
DoCmd.Close acForm, Me.Name
Exit Sub
Else
DoCmd.OpenForm "frmDataEntry"
DoCmd.Close acForm, Me.Name
DoCmd.Close acForm, "frmMainMenu"
End If
我的代码运行,我从SQL数据中检索了1条记录。我的问题是我无法弄清楚如何使用数据填充表单。谁能解释我如何使用这些数据来填写表格?
答案 0 :(得分:0)
使用表单的“ where”子句。 (不要与打开时的过滤器选项混淆-不要使用它。)
所以您可以这样做:
dim strWhere as string
strWhere = "tblOrders.VendorId <> 774 AND tblOrders.OrderID = " & strReq
docmd.OpenForm "frmDataEntry",,,strWhere
因此,如果表单具有vendorID和da orderid,则该表单将打开一个记录。 当然,您可以添加其他代码,但是可以根据上述内容,通过“ where”子句对两行代码进行过滤/设置并将表单打开到ONE记录中。
您实际上不必建立新的查询或做任何事情。
答案 1 :(得分:0)
问题出在我没有将表格绑定到数据的顺序中。 SQL查询正在完成它的工作,我没有将其用作表单数据源。工作代码如下所示。
Case "Req"
Me.cmdDone.SetFocus
GotoSearchTextbox
If IsNull(Me.txtSearchTerm) Then 'Blank, show them all!
DoCmd.OpenForm "frmDataEntry"
DoCmd.Close acForm, Me.Name
DoCmd.Close acForm, "frmMainMenu"
Else
Dim Req As Integer 'OrderId entered do the search
Req = Me.txtSearchTerm
StrSql = "SELECT tblOrders.*, tblFleetVendors.* FROM tblOrders INNER JOIN tblFleetVendors ON tblOrders.VendorId = tblFleetVendors.VendorID"
StrSql = StrSql & " WHERE (((tblOrders.Org)=DLookUp(""[DivisionOrg]"",""tblSetup""))"
StrSql = StrSql & "AND ((tblOrders.VendorId)<>774) AND ((tblOrders.OrderID)=" & Req & "));"
Set db = CurrentDb()
Set qdf = db.QueryDefs("qryOrders")
qdf.SQL = StrSql
Set rst = db.OpenRecordset("qryOrders", dbOpenDynaset, dbSeeChanges)
intRecords = rst.RecordCount
If intRecords <= 0 Then
MsgBox "There are no records that match your search"
Set rst = Nothing
Set db = Nothing
rst.Close
DoCmd.Close acForm, Me.Name
Exit Sub
Else
DoCmd.Close acForm, Me.Name
DoCmd.OpenForm "frmDataEntry"
Form!frmDataEntry.RecordSource = StrSql
DoCmd.Close acForm, "frmMainMenu"
End If
End If