我有一个访问表,我按日期范围搜索。在表单中我有一个文本框TxtTotal,我想显示过滤范围内的代码我有的代码。继续给我完整的记录数,而不是过滤范围。
这是我的模块
Function FindRecordCount(strSQL As String) As Long
Dim db As Database
Dim rstRecords As Recordset
'On error GoTo ErrorHandler
Set db = CurrentDb
Set rstRecords = db.OpenRecordset("TblPurchases")
If rstRecords.EOF Then
FindRecordCount = 0
Else
rstRecords.MoveLast
FindRecordCount = rstRecords.RecordCount
End If
rstRecords.Close
db.Close
Set rstRecords = Nothing
Set db = Nothing
End Function
这是我在表单上的TxtTotal文本框的代码
Sub Search()
Dim strCriteria, task As String
Me.Refresh
If IsNull(Me.TxtPurchaseDateFrom) Or IsNull(Me.TxtPurchaseDateTo)
Then
MsgBox "Please enter the date range", vbInformation, "Date Range
Required"
Me.TxtPurchaseDateFrom.SetFocus
Else
strCriteria = "([Date of Purchase] >= #" & Me.TxtPurchaseDateFrom &
"# and [Date of Purchase] <= #" & Me.TxtPurchaseDateTo & "#)"
task = "select * from TblPurchases where( " & strCriteria & ") order
by [Date of Purchase] "
DoCmd.ApplyFilter task
Me.TxtTotal = FindRecordCount(task)
End If
结束子
结果不断给我完整的记录数,而不是过滤范围。
我认为主要问题是这一行:
Set rstRecords = db.OpenRecordset("TblPurchases")
您正在设置记录集以使用表作为其源而不是SQL字符串。无论您的输入日期是什么,如果您正在查看整个表格,它将返回整个表格xD。
至于从查询结果中查找项目的总数,使用SQL COUNT函数可能是有意义的,例如:SELECT COUNT(<Column>) FROM <table> WHERE <criteria>;
这将为您提供从该查询提供的数据条目的数量。
我还建议使用QueryDef对象作为SQL定义,因为它使事情变得更清晰。但同样,这只是一个推荐EG:
Function FindRecordCount(dateFrom As Date, dateTo As Date) As Long
Dim db As DAO.Database
Dim QDF As DAO.QueryDef
Dim rstRecords As DAO.Recordset
Dim SQL As String
SQL = "SELECT COUNT(*) FROM TblPurchase WHERE([Date of Purchase] >= #@dateFrom# AND [Date of Purchase] <= #@dateTo#)"
Set db = CurrentDb
Set QDF = db.QuerDefs(SQL)
QDF.Paramaters("@dateFrom").Value = dateFrom
QDF.Paramaters("@dateTo").Value = dateTo
Set rstRecords = QDF.OpenRecordset("TblPurchases")
If rstRecords.EOF Then
FindRecordCount = 0
Else
rstRecords.MoveLast
FindRecordCount = rstRecords.RecordCount
End If
rstRecords.Close
QDF.Close
db.Close
Set rstRecords = Nothing
Set QDF = Nothing
Set db = Nothing
End Function
最好的祝福。
您可以使用文本框txtTotal
的ControlSource中的DCount表达式替换所有这些:
=DCount("*","TblPurchase ","[Date of Purchase] Between #" & Format(Nz(Me!TxtPurchaseDateFrom.Value,Date()), "yyyy\/mm\/dd") & "# And #" & Format(Nz(Me!TxtPurchaseDateTo.Value,Date()), "yyyy\/mm\/dd") & "#")