使用文本框作为Access 2016中列表框的条件

时间:2019-05-22 18:59:22

标签: sql vba ms-access

我有一个包含3个列表框的表单,我试图根据2个输入/文本框给出的范围进行查询。我不确定如何获取脚本来查看文本框。

Me.lstDailytop.RowSource = " SELECT StockCode, SumOfQTY, Date from qrytpdailystck WHERE [Date] BETWEEN  Me.txtStart.Value And Me.txtEnd.Value"

Me.lstMonthlytop.RowSource = " SELECT StockCode, SumOfQTY, Date from qrytpmonthstck WHERE [Date] BETWEEN Me.txtStart.Value AND Me.txtEnd.Value "

Me.lstYearlytop.RowSource = " SELECT StockCode, SumOfQTY, Date from qrytpyearstck WHERE [Date] BETWEEN Me.txtStart.Value AND Me.txtEnd.Value "

运行此命令时,它会要求输入Me.txtStart.valueMe.txtEnd.value的值。我假设有一种方法可以让VBA知道它是指对象而不是变量。我无法弄清楚。希望有人知道我在做什么错。

1 个答案:

答案 0 :(得分:1)

简单地将需要从字符串转换为日期的值进行连接,请确保在辅助语句后也Requery

Dim whereClause As String

whereClause = " WHERE [Date] BETWEEN CDate('" & Me.txtStart.Value & "')" _
                 & "             AND CDate('" & Me.txtEnd.Value & "')"

Me.lstDailytop.RowSource = "SELECT StockCode, SumOfQTY, [Date] FROM qrytpdailystck " & whereClause
Me.lstDailytop.Requery

Me.lstMonthlytop.RowSource = "SELECT StockCode, SumOfQTY, [Date] FROM qrytpmonthstck " & whereClause
Me.lstMonthlytop.Requery

Me.lstYearlytop.RowSource = "SELECT StockCode, SumOfQTY, [Date] FROM qrytpyearstck " & whereClause
Me.lstYearlytop.Requery

或者,您可以放弃构建串联的SQL字符串,而直接在具有绝对引用的表单控件上使用一个查询语句。表单日期值是否为空,使用NZ()查询可以解决问题。

SQL (将下面的语句作为默认分配保存在属性表下每个组合框各自的RowSource中,请勿更改)

SELECT StockCode, SumOfQTY, [Date] 
FROM qrytpdailystck
WHERE [Date] BETWEEN NZ(Forms!myFormName!txtStart, [Date])
                 AND NZ(Forms!myFormName!txtEnd, [Date])

SELECT StockCode, SumOfQTY, [Date] 
FROM qrytpmonthstck
WHERE [Date] BETWEEN NZ(Forms!myFormName!txtStart, [Date])
                 AND NZ(Forms!myFormName!txtEnd, [Date])

SELECT StockCode, SumOfQTY, [Date] 
FROM qrytpyearstck
WHERE [Date] BETWEEN NZ(Forms!myFormName!txtStart, [Date])
                 AND NZ(Forms!myFormName!txtEnd, [Date])

VBA (在宏或模块中的所需触发事件下方运行)

Me.lstDailytop.Requery    
Me.lstMonthlytop.Requery    
Me.lstYearlytop.Requery