Filter 和 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/region to filter on:"))   If strCountry <> "" Then
      ' 打开已筛选的记录集对象。
      Set rstPublishersCountry = _
         FilterField(rstPublishers, "Country", strCountry)      If rstPublishersCountry.RecordCount = 0 Then
         MsgBox "No publishers from that country/region."
      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
www.51windows.Net