Excel VBA-遍历记录集 [英] Excel VBA - Loop through recordset
本文介绍了Excel VBA-遍历记录集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
遍历记录集时遇到问题;这是代码:
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
当我检查记录集有多少行时,它返回4,但在循环中仅进行一次.在这种情况下,它应该循环4次.
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.
推荐答案
您在循环之前使用了movelast
,因此,如果要实际迭代所有记录,则需要movefirst
.
You used movelast
before the loop so you'll need to movefirst
if you want to actually iterate all the records.
这篇关于Excel VBA-遍历记录集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文