使用 RecordCount 属性可确定 Recordset 对象中记录的数目。ADO 无法确定记录数时该属性返回 –1。读已关闭的 Recordset 上的 RecordCount 属性将产生错误。如果 Recordset 对象支持近似定位或书签(即 Supports (adApproxPosition) 或 Supports (adBook) 各自返回 True),不管是否完全填充该值,该值将为 Recordset 中记录的精确数目。如果 Recordset 对象不支持近似定位,该属性可能由于必须对所有记录进行检索和计数以返回精确 RecordCount 值而严重消耗资源
该范例使用 Filter 属性打开一个新的 Recordset,它基于适用于已有 Recordset 的指定条件。它使用 RecordCount 属性显示两个 Recordsets 中的记录数。该过程运行时需要 FilterField 函数。Public Sub FilterX() Dim rstPublishers As ADODB.Recordset
Dim rstPublishersCountry As ADODB.Recordset
Dim strCnn As String
Dim intPublisherCount As Integer
Dim strCountry As String
Dim strMessage As String ' 使用出版商表中的数据打开记录集。
strCnn = "Provider=sqloledb;" & _
"Data Source=srv;Initial Catalog=pubs;User Id=sa;Password=; "
Set rstPublishers = New ADODB.Recordset
rstPublishers.CursorType = adOpenStatic
rstPublishers.Open "publishers", strCnn, , , adCmdTable ' 充填记录集。
intPublisherCount = rstPublishers.RecordCount ' 让用户输入。
strCountry = Trim(InputBox( _
"Enter a country to filter on:")) If strCountry <> "" Then
' 打开已筛选的记录集对象。
Set rstPublishersCountry = _
FilterField(rstPublishers, "Country", strCountry) If rstPublishersCountry.RecordCount = 0 Then
MsgBox "No publishers from that country."
Else
' 打印原始记录集和已筛选记录集对象的记录数。
strMessage = "Orders in original recordset: " & _
vbCr & intPublisherCount & vbCr & _
"Orders in filtered recordset (Country = '" & _
strCountry & "'): " & vbCr & _
rstPublishersCountry.RecordCount
MsgBox strMessage
End If
rstPublishersCountry.Close End IfEnd SubPublic Function FilterField(rstTemp As ADODB.Recordset, _
strField As String, strFilter As String) As ADODB.Recordset ' 在指定的记录集对象上设置筛选操作并打开一个新的记录集对象。
rstTemp.Filter = strField & " = '" & strFilter & "'"
Set FilterField = rstTempEnd Function注意 当已知要选择的数据时,使用 SQL 语句打开 Recordset 通常更为有效。该范例说明了如何创建唯一的 Recordset 并从特定的国家(地区)获得记录。Public Sub FilterX2() Dim rstPublishers As ADODB.Recordset
Dim strCnn As String ' 使用出版商表中的数据打开记录集。
strCnn = "Provider=sqloledb;" & _
"Data Source=srv;Initial Catalog=pubs;User Id=sa;Password=; "
Set rstPublishers = New ADODB.Recordset
rstPublishers.CursorType = adOpenStatic
rstPublishers.Open "SELECT * FROM publishers " & _
"WHERE Country = 'USA'", strCnn, , , adCmdText
' 打印记录集中的当前数据。
rstPublishers.MoveFirst
Do While Not rstPublishers.EOF
Debug.Print rstPublishers!pub_name & ", " & _
rstPublishers!country
rstPublishers.MoveNext
Loop rstPublishers.CloseEnd Sub
解决方法很简单
一是设置游标,二是先加一句movelast
if rs.recordcount>0 then
rs.movelast
rs.movefirst
msgbox rs.recordcount
end if
rs.MoveLast
rs.MoveFirst
msgbox rs.RecordCount2. rs.CursorType = adOpenKeyset or rs.CursorType = adOpenStatic
msgbox rs.RecordCount3. rs.CursorType = adOpenForwardOnly
msgbox rs.RecordCount 'return -1
rs.Open sqlstr, conn, adOpenKeyset, adLockPessimistic
用如上语句打开数据库,数据库中无记录,为何rs.AbsolutePosition=1,且rs.recordcount=1