在Access中使用OpenRecordset

时间:2017-06-11 21:28:46

标签: vba

为什么如果我使用这段代码片段,我只会输出一条记录?

Dim sav1 As DAO.Database
Dim rec As DAO.Recordset
Set sav1 = CurrentDb

Set rec = sav1.OpenRecordset(Text2)

1 个答案:

答案 0 :(得分:1)

RecordCount属性不可靠。在滚动所有Recordset之前它没用。

Set rec = sav1.OpenRecordset(Text2)
rec.MoveLast ' <--- necessary to have all records in the `RecordCount`
rec.MoveFirst ' <--- re-seeks the recordset to its beginning
For i = 1 to rec.RecordCount ' <--- now you will have the correct count

通常建议不要使用RecordCount属性,而是在循环中逐个记录记录集,即

Do Until rec.EOF
  ' ...
  ' do something with the current record
  ' ...

  rec.MoveNext ' <-- move to next record and loop
Loop