The below code exports data correctly however my debug.print
line always gives -1. I would like to retrieve the count of rows in debug.print
statement. 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
When you open a RecordSet
as ForwardOnly
(default if you don't explicit declare the cursor type) the RecordCount property returns -1.
For more check here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.