10 tips when using VBA Recordset objects
1. 查閱傳遞
Loop一個Recordset之前,先檢查Recordset object是否為空.
BOF為真,假如現時指針位置在第一條記錄之前. EOF為真,假如現時指針位置在最後一條記錄之後.
於是,只要兩者同時為真,證明Recordset為空集.
2. 查看record count
ADO Recordset
假如recordcount=-1,表示為空集
3. 不能一直使用rs.MoveNext
使用rs.MoveNext之前,需先確認current record在BOF與EOF之間
...do something...
rs.MoveNext
正確做法:
If rs![fieldname] = value Then
...do something...
End If
rs.MoveNext
Loop
4. 死循環
切記假如rs.MoveNext
5. 使用Recordset.find時,避免no match error
用rs.find(criteria)搜索record時,假如沒有搜到任何record的時候,會報錯. 於是,利用rs.NoMatch,確保有結果之後,再進行操作.
If Not rs.NoMatch Then
...do something...
End If
6. 強制新加入的Record為現時Record
當往一個Recordset中加入,一條新的Record后,需要強制更新.
rs.Bookmark = rs.LastModified
7. ADO的Find不支持IS
當用ADO搜索NULL的時候,不能使用下述代碼,否則報錯.
8. ADO不支持AND
下面語句會報錯
需改為Filter
9. 謹記close一個Recordset
10. 後記
Postscript: DAO vs. ADO
Within the Visual Basic world, there are two Recordset objects: Recordset and Recordset1 (new with 2007). It’s important to remember that neither the DAO nor ADO versions of these objects are interchangeable, as they support different methods, properties, and events. That can be confusing if you think ADO is just an improved or later upgrade of DAO. In fact, the two libraries solve different problems. DAO was designed specifically for the Microsoft Jet database engine. ADO was designed for OLE DB providers and can be much simpler and more flexible than DAO. However, DAO is almost always more efficient when working directly with Jet.
Know how you plan to use a Recordset and then use the most appropriate library. My best advice is to choose one library and use it exclusively when possible. The similarities and differences are too numerous to list here, but you can find information online: