Excel VBA - 循环记录集

时间:2014-09-15 11:24:18

标签: excel-vba recordset vba excel

循环记录集时遇到问题;这是代码:

    Dim query as String
    query = "SELECT * FROM test WHERE " & filter

    ' Declare variables'
    Dim objMyConn As ADODB.Connection
    Dim objMyCmd As ADODB.Command
    Dim objMyRecordset As ADODB.Recordset
    Dim objRst As ADODB.Recordset

    Set objMyConn = New ADODB.Connection
    Set objMyCmd = New ADODB.Command
    Set objMyRecordset = New ADODB.Recordset

    'Open Connection'
    objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=MyServer;Initial Catalog=MyDB;User ID=test;Password=test"
    objMyConn.Open

    'Set and Excecute SQL Command'
    Set objMyCmd.ActiveConnection = objMyConn
    objMyCmd.CommandText = query
    objMyCmd.CommandType = adCmdText

    'Open Recordset'
    Set objMyRecordset.Source = objMyCmd
    objMyRecordset.CursorLocation = adUseClient
    objMyRecordset.CursorType = adOpenStatic
    objMyRecordset.Open

    Dim FindRecordCount As Integer
    If objMyRecordset.EOF Then
        FindRecordCount = 0
    Else
        objMyRecordset.MoveLast
        FindRecordCount = objMyRecordset.RecordCount ' In this case it returns 4
    End If

     Do Until objMyRecordset.EOF = True
        ' Get variables

        ...

        ' Move to next Record
        objMyRecordset.MoveNext
     Loop

当我检查记录集有多少行时,它返回4,但只循环一次。在这种情况下,它应循环4次。

2 个答案:

答案 0 :(得分:2)

您在循环之前使用了movelast,因此如果您想要实际迭代所有记录,则需要movefirst

答案 1 :(得分:1)

你不需要写" EOF = true" " EOF"在完全相同的情况下公式是正确的:)