ADODB RecordSet.RecordCount属性始终返回-1

时间:2015-10-02 09:09:03

标签: sql excel-vba tsql count recordset

以下代码正确导出数据,但我的debug.print行总是给出-1。我想在debug.print语句中检索行数。请说明出了什么问题。

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

2 个答案:

答案 0 :(得分:1)

尝试指定光标位置。在打开连接之前指定光标位置。

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

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

答案 1 :(得分:0)

当您打开 Ind_name Year Correlation Beta 1: A 2001 NA 0.0000000 2: A 2002 1 0.3076923 3: A 2003 1 0.4545455 RecordSet时(默认情况下,如果您没有明确声明游标类型),RecordCount属性返回-1。

有关详情here