Excel VBA - 循环遍历记录集

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25846954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 08:56:11  来源:igfitidea点击:

Excel VBA - Loop through recordset

excel-vbarecordsetvbaexcel

提问by SparX23

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.

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

回答by Rory

You used movelastbefore the loop so you'll need to movefirstif you want to actually iterate all the records.

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

回答by Mike

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

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