我可以输入一个'?'在传递查询的日期范围内,以便我可以在Access中的表单中输入日期范围?

时间:2014-11-03 22:01:56

标签: sql access-vba

在访问中是否有一种方法可以创建不保留硬编码日期的传递查询?例如,我有一个链接到传递查询的表单,我希望能够通过表单输入日期范围,并让它更新传递查询。这是我当前的查询,但我更喜欢它是带有'?'的日期范围或允许提示日期范围或我通过表单输入日期范围的东西。可以这样做吗?或者我必须使用VBA吗?

select distinct fill_sold_dt ,pf.str_nbr,wic_nbr, pkg_sz, pkg_qty, sum(fill_qty_dspn), sum((fill_qty_dspn)/(pkg_sz*pkg_qty) ) as Packs 
 from
prdedwvwh.prescription_fill_sold pf, prdedwvwh.location_store_address_cur lsa, prdedwvwh.drug_cur d
where pf.str_nbr=lsa.str_nbr and
d.drug_id=pf.drug_id
and fill_sold_dt(DATE) >= CURRENT_DATE - 7
 and wic_nbr in (683378,335776,418723)

group by 1,2,3,4,5

1 个答案:

答案 0 :(得分:0)

您必须使用VBA。 如果您不知道如何在VBA中完成此操作,可以在此页面上查看示例2: http://support.microsoft.com/kb/131534

编辑 - 添加完整示例

在表单上创建2个日期类型的文本框,并将它们命名为DateStart和DateEnd

创建一个带有点击事件的按钮,如下所示:

Private Sub Command0_Click()

    GetDataFromDate DateStart.value, DateENd.value

End Sub

并将此Sub添加到您的表单中:

Sub GetDataFromDate(dtStart As Date, dtEnd As Date)

 Dim MyDb As Database, MyQry As QueryDef, MyRS  As Recordset
 Set MyDb = CurrentDb()
 Set MyQry = MyDb.CreateQueryDef("")

 ' Type a connect string using the appropriate values for your
 ' server.
 MyQry.Connect = "ODBC;DSN=user1;UID=user1;PWD=user1;DATABASE=TEST"

 ' Set the SQL query with Date Range passed to the sub as parameters
 MyQry.SQL = " SELECT distinct fill_sold_dt ,pf.str_nbr,wic_nbr, pkg_sz, pkg_qty, sum(fill_qty_dspn) as som, sum((fill_qty_dspn)/(pkg_sz*pkg_qty) ) as Packs " & _
             " FROM prdedwvwh.prescription_fill_sold pf, prdedwvwh.location_store_address_cur lsa, prdedwvwh.drug_cur d " & _
             " WHERE pf.str_nbr=lsa.str_nbr and d.drug_id = pf.drug_id and wic_nbr in (683378,335776,418723)" & _
             "   AND fill_sold_dt BETWEEN #" & dtStart & "# AND #" & dtEnd & "# " & _
             " GROUP BY 1,2,3,4,5 "

 MyQry.ReturnsRecords = True
 Set MyRS = MyQry.OpenRecordset()

 MyRS.MoveFirst

 If Not MyRS.BOF Then

    While Not MyRS.EOF

        Debug.Print MyRS!fill_sold_dt
        Debug.Print MyRS!str_nbr
        Debug.Print MyRS!pkg_sz
        Debug.Print MyRS!som
        Debug.Print MyRS!Packs

        MyRS.MoveNext
    Wend


 End If

 MyQry.Close
 MyRS.Close
 MyDb.Close

End Sub

你去吧