记录集总是返回 -1 (excel VBA)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20676416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 01:02:09  来源:igfitidea点击:

Recordset always returns -1 (excel VBA)

excel-vbams-access-2010vbaexcel

提问by Kentot

I want to count the number of rows returned by a query in a recordset, I tried recset.RecordCountfunction but it always return a value of -1.

我想计算记录集中查询返回的行数,我尝试了recset.RecordCount函数,但它总是返回-1.

How am I going to count the number of records or rows in recordset?

我将如何计算记录集中的记录数或行数?

回答by Marcin W?asny

It is important to specify parameter: CursorLocation = adUseClient in connection object.

在连接对象中指定参数:CursorLocation = adUseClient 很重要。

dbName = "DbInjectorsCatalog"
dbFilePath = "C:\DbInjectorsCatalog.mdf"

connStr = "Driver={SQL Server native Client 11.0};" & _
          "Server=(LocalDB)\v11.0;" & _
          "AttachDBFileName=" & dbFilePath & ";" & _
          "Database=" & dbName & ";" & _
          "Trusted_Connection=Yes"
sqlStr = "Select * from Injectors"

Set conn = New ADODB.Connection
conn.ConnectionString = connStr

conn.CursorLocation = adUseClient

conn.CursorLocation = adUseClient

conn.Open
Set rs = New ADODB.Recordset
rs.Open sqlStr, connStr, adOpenStatic, adLockBatchOptimistic 

Full working example is here: http://straightitsolutions.blogspot.com/2014/12/read-recordcount-from-adodbrecordset.html

完整的工作示例在这里:http: //straightitsolutions.blogspot.com/2014/12/read-recordcount-from-adodbrecordset.html

回答by gaurav5430

have you tried moving to the last before checking for count

在检查计数之前,您是否尝试移动到最后一个

recset.MoveLast

also see if this helps

也看看这是否有帮助

The RecordCount property will return -1 for a forward-only cursor; the actual count for a static or keyset cursor; and either -1 or the actual count for a dynamic cursor, depending on the data source.

RecordCount 属性将为只进游标返回 -1;静态或键集游标的实际计数;和 -1 或动态游标的实际计数,具体取决于数据源。

Check this question:

检查这个问题:

VB6 ADODB.Recordset RecordCount property always returns -1

VB6 ADODB.Recordset RecordCount 属性总是返回 -1

回答by Sai Avinash

can you try adding this:

你可以尝试添加这个:

objRS.CursorLocation = adUseClient
objRS.Open strSQL, objConn,,adLockReadOnly, adCmdText

The Cursor position is important.

光标位置很重要。

Hope this helps..

希望这可以帮助..

回答by Andrew

If I remember correctly a recordset count isn't populated until you move to the end. I believe (dredging my memory here) that it is something like

如果我没记错的话,直到您移动到最后才会填充记录集计数。我相信(在这里挖掘我的记忆)它就像

MyRecordSet.MoveLast
MyRecordSet.MoveFirst

Then your count should be populated

那么你的计数应该被填充