问题
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