ADODB Recordset.RecordCount giving incorrect answer

谁都会走 提交于 2019-12-12 03:33:42

问题


I have an issue with my Recordset returning -1 as the RecordCount when in fact there are 1164 records.

I have checked my query which is fine. Even though it tells me there are -1 records the CopyFromRecordset method still works and pastes the correct results. Never had an issue before using the rs.RecordCount?

Dim strSQL As String
Dim rs As New ADODB.Recordset

If cust = "JPM" Then
    port = "RP L99"
Else
    port = "RP V10"
End If

strSQL = "my select query"

rs.Open strSQL, cn, adOpenKeyset, adLockOptimistic
rs.MoveFirst
GetCompanies = rs.RecordCount
If GetCompanies > 0 Then
   wsLive.Range("A" & ROWCOMPANYSTART).CopyFromRecordset rs
   wsLive.Range("C" & ROWCOMPANYSTART & ":C" & GetCompanies + ROWCOMPANYSTART).NumberFormat = "0.00%"
End If
CloseRecordset rs

End Function

回答1:


To get the actual count, you need to first move the cursor to the last record then move back to the beginning. However, remember for a large dataset, the moving back and forth will be an inefficient task. So, I would suggest the following with caution.

    Dim strSQL As String
    Dim rs As New ADODB.Recordset

    If cust = "JPM" Then
        port = "RP L99"
    Else
        port = "RP V10"
    End If

    strSQL = "my select query"

    rs.CursorType = adOpenDynamic

    rs.Open strSQL, cn, adOpenKeyset, adLockOptimistic

    If Not (rs.BOF And rs.EOF) Then
        rs.MoveLast
        rs.MoveFirst
        GetCompanies = rs.RecordCount
        wsLive.Range("A" & ROWCOMPANYSTART).CopyFromRecordset rs
        wsLive.Range("C" & ROWCOMPANYSTART & ":C" & GetCompanies + ROWCOMPANYSTART).NumberFormat = "0.00%"      
    'Else
        'MsgBox "No Records !!"
    End If

    CloseRecordset rs
End Function


来源:https://stackoverflow.com/questions/30169900/adodb-recordset-recordcount-giving-incorrect-answer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!