简体   繁体   English

ADODB RecordSet.RecordCount 属性总是返回 -1

[英]ADODB RecordSet.RecordCount property always returns -1

The below code exports data correctly however my debug.print line always gives -1.下面的代码正确导出数据,但是我的debug.print行总是给出 -1。 I would like to retrieve the count of rows in debug.print statement.我想检索debug.print语句中的行数。 Please suggest what is wrong.请提出什么问题。

Sub TEST()

        Dim rs As Object
        Dim iCols As Integer
        Set rs = CreateObject("ADODB.Recordset")
        On Error GoTo ERR
        Dim SQLSTR As String, MYVAL As String
        MYVAL = InputBox("Enter Query")
        SQLSTR = " " & MYVAL & ""
        CONNECT_TO_DWHS
        rs.Open SQLSTR, PERSONALDBCONT

            For iCols = 0 To rs.Fields.Count - 1
                ActiveSheet.Cells(1, iCols + 1).Value = rs.Fields(iCols).Name
            Next
         Debug.Print rs.RecordCount
        ActiveSheet.Cells(2, 1).CopyFromRecordset rs
        ActiveSheet.Cells(1, 1).Select

        CLOSE_CONNECTION_TO_SQL

            With ActiveWindow
                .SplitColumn = 0
                .SplitRow = 1
                .FreezePanes = True
            End With

        Exit Sub

   ERR:
        CLOSE_CONNECTION_TO_SQL
        MsgBox "There was an error"

  End Sub

Try to specify the cursor location.尝试指定光标位置。 Specify the cursor location before opening the connection.在打开连接之前指定光标位置。

rs.CursorLocation = adUseClient
rs.Open SQLSTR, PERSONALDBCONT
For iCols = 0 To rs.Fields.Count - 1
  ActiveSheet.Cells(1, iCols + 1).Value = rs.Fields(iCols).Name
Next
Debug.Print rs.RecordCount

Please read this article: http://www.geeksengine.com/article/recordcount-ado-recordset-vba.html请阅读这篇文章: http : //www.geeksengine.com/article/recordcount-ado-recordset-vba.html

When you open a RecordSet as ForwardOnly (default if you don't explicit declare the cursor type) the RecordCount property returns -1.当您以ForwardOnly打开RecordSet (如果您不显式声明游标类型, ForwardOnly默认值),RecordCount 属性返回 -1。

For more check here .欲了解更多信息,请点击此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM