【问题标题】:how to get the number of records in excel vba recordeset如何获取excel vba记录集中的记录数
【发布时间】:2017-04-22 22:55:56
【问题描述】:

我想在 Excel 中使用 vba 获取记录集中的记录总数,我使用了下面的代码,但它没有运行。或许能帮帮我!

 Set cn = CreateObject("ADODB.Connection")
    strConnection = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" &   Application.ActiveWorkbook.Path & "\infodb.mdb"
    cn.Open strConnection

strSql = "SELECt * FROM tbl_hoze"
        Set rs = cn.Execute(strSql)
            rs.MoveLast
            MsgBox rs.RecordCount

【问题讨论】:

  • 您遇到错误了吗?在哪里?您的代码遇到的确切问题是什么?
  • 如果你只想要计数,那么strSql = "SELECT count(*) as numRecs FROM tbl_hoze" 应该更有效。

标签: sql excel vba recordset


【解决方案1】:

假设您的 SQL 语句成功执行并且您获得了记录集,我将获得数组中的行并使用该数组来做任何我想做的事情。 RecordCount 函数有时会失败,这在我身上经常发生。

此外,我不知道您为什么要在打印记录数之前使用 rs.MoveLast。删除它或将其移动到 msgbox 行之后,看看会发生什么。简而言之,你会这样做:

dim arr() as variant

arr=rs.GetRows()

【讨论】:

  • 嗨,如果我删除 rs.MoveLast,它会在结果中显示 -1
  • 我使用下面的代码但结果不正确:strSql = "SELECt * FROM tbl_hoze" Set rs = cn.Execute(strSql) arr = rs.GetRows() MsgBox UBound(arr)
  • @sasanmohammadi .GetRows() 返回一个二维数组,其中列是第一个维度,行是第二个维度。 MsgBox UBound(arr, 2) 将返回行数。或者,您可以转置数组:arr = Application.Transpose(rs.GetRows)
【解决方案2】:

每当我使用 SQL Server 数据库时,我都会遇到这个问题(与 Access 的关系不大)。所以我制定了这个快速函数,它应该能够为您提供 SQL Server 记录集的行数。

Private Function GetSQLRecordCount(rs As Recordset) As Integer

    Dim retVal As Integer: retVal = 0
    On Error GoTo NOROWSRETURNED
        Dim counterArray() As Variant: counterArray = rs.GetRows()
        retVal = UBound(counterArray, 2) - LBound(counterArray, 2) + 1
    On Error GoTo 0

    GetSQLRecordCount = retVal

    Exit Function
NOROWSRETURNED:
    retVal = 0
    GetSQLRecordCount = retVal

End Function

我最近一直在使用这个,而且非常可靠。

【讨论】:

    猜你喜欢
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多