GetRows 方法范例

该范例使用 GetRows 方法从 Recordset 中检索指定数目的行,并将结果数据填充到数组。在两种情况下 GetRows 方法返回的行将少于所需的数目:一种情况是因为达到了 EOF,另一种情况是因为 GetRows 试图检索已被其他用户删除的数据。仅当第二种情况发生时函数将返回 False。运行该过程需要使用 GetRowsOK 函数。

Public Sub GetRowsX()

   Dim rstEmployees As ADODB.Recordset

   Dim strCnn As String

   Dim strMessage As String

   Dim intRows As Integer

   Dim avarRecords As Variant

   Dim intRecord As Integer

   ' 使用雇员表中的姓名和受雇日期打开记录集。

      strCnn = "Provider=sqloledb;" & _

      "Data Source=srv;Initial Catalog=pubs;User Id=sa;Password=; "

   Set rstEmployees = New ADODB.Recordset

   rstEmployees.Open "SELECT fName, lName, hire_date " & _

      "FROM Employee ORDER BY lName", strCnn, , , adCmdText

   Do While True

      ' 得到用户输入的行数。

      strMessage = "Enter number of rows to retrieve."

      intRows = Val(InputBox(strMessage))

      If intRows <= 0 Then Exit Do

      ' 如 GetRowsOK 成功则打印结果,请注意是否达到文件末端。

      If GetRowsOK(rstEmployees, intRows, _

            avarRecords) Then

         If intRows > UBound(avarRecords, 2) + 1 Then

            Debug.Print "(Not enough records in " & _

               "Recordset to retrieve " & intRows & _

               " rows.)"

         End If

         Debug.Print UBound(avarRecords, 2) + 1 & _

            " records found."

         ' 打印已检索的数据。

         For intRecord = 0 To UBound(avarRecords, 2)

            Debug.Print "  " & _

               avarRecords(0, intRecord) & " " & _

               avarRecords(1, intRecord) & ", " & _

               avarRecords(2, intRecord)

         Next intRecord

      Else

         ' 假定 GetRows 错误源于其他用户对数据的更改,

         ' 使用 Requery 刷新 Recordset 并重新开始。

         If MsgBox("GetRows failed--retry?", _

               vbYesNo) = vbYes Then

            rstEmployees.Requery

         Else

            Debug.Print "GetRows failed!"

            Exit Do

         End If

      End If

      ' 由于使用 GetRows 使当前记录指针指向访问过的最后一个记录,

      ' 所以,在循环回到另一次搜索前将记录指针移回 Recordset 的开始。

      rstEmployees.MoveFirst

   Loop

   rstEmployees.Close

End Sub

Public Function GetRowsOK(rstTemp As ADODB.Recordset, _

   intNumber As Integer, avarData As Variant) As Boolean

   ' 将 GetRows 方法的结果保存在数组中。

   avarData = rstTemp.GetRows(intNumber)

   ' 仅当返回的行数少于所需的行数而非由于到达了 Recordset 末端时才返回 False。

   If intNumber > UBound(avarData, 2) + 1 And _

         Not rstTemp.EOF Then

      GetRowsOK = False

   Else

      GetRowsOK = True

   End If

End Function