Excel VBA - Loop through recordset

这一生的挚爱 提交于 2019-12-23 04:45:15

问题


I have an issue when looping through a recordset; here is the code:

    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

When I check how many rows has the recordset , it returns 4, but goes only once through the loop. In this case, it should loop 4 times.


回答1:


You used movelast before the loop so you'll need to movefirst if you want to actually iterate all the records.




回答2:


You don't need to write "EOF=true" the "EOF" formula is true in exactly the same situations :)



来源:https://stackoverflow.com/questions/25846954/excel-vba-loop-through-recordset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!