如何将记录计入访问表单的文本框中

时间:2019-04-29 23:29:48

标签: access-vba

我有一个按日期范围进行搜索的访问表。在表单中,我有一个文本框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

结束子

结果不断给我完整的记录数,而不是过滤的范围。

2 个答案:

答案 0 :(得分:0)

我相信主要的问题是这一行:

Set rstRecords = db.OpenRecordset("TblPurchases")

您正在设置“记录”集以使用表作为其源,而不是SQL字符串。无论您输入的日期是什么,如果您查看整个表格,它将返回整个表格的xD。

对于从查询结果中查找项目总数,可以使用SQL COUNT函数,例如:SELECT COUNT(<Column>) FROM <table> WHERE <criteria>;,这将为您提供该查询提供的数据条目的数量。 / p>

我还建议您将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

最好的问候。

答案 1 :(得分:0)

您可以在文本框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") & "#")