ado 」标签的归档

10 tips when using VBA Recordset objects

1. 查閱傳遞

Loop一個Recordset之前,先檢查Recordset object是否為空.

If Not(rs.BOF And rs.EOF) Then

BOF為真,假如現時指針位置在第一條記錄之前. EOF為真,假如現時指針位置在最後一條記錄之後.

於是,只要兩者同時為真,證明Recordset為空集.

2. 查看record count

ADO Recordset

If Not(rst.BOF And rst.EOF) Then

假如recordcount=-1,表示為空集

3. 不能一直使用rs.MoveNext

使用rs.MoveNext之前,需先確認current record在BOF與EOF之間

If rs![fieldname] = value Then

  ...do something...

rs.MoveNext

正確做法:

  Do While Not rs.EOF

  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,確保有結果之後,再進行操作.

rs.Find searchcriteria

If Not rs.NoMatch Then

  ...do something...

End If

6. 強制新加入的Record為現時Record

當往一個Recordset中加入,一條新的Record后,需要強制更新.

rs.Update

rs.Bookmark = rs.LastModified

7. ADO的Find不支持IS

當用ADO搜索NULL的時候,不能使用下述代碼,否則報錯.

rst.Find "LastName Null"

8. ADO不支持AND

下面語句會報錯

rs.FindNext "SupplierID = 10 And CategoryID = 4"

需改為Filter

rs.Filter = "SupplierID = 10 AND CategoryID = 4"

9. 謹記close一個Recordset

rs.Close

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:

Ref

article clipper remember 10 tips when using VBA Recordset objects
 

ADO Incorrect RecordCount

使用ADO的時候,最好還是先驗證一下它的recordcount,確保所有東西都正確了才繼續編程.

當發現ADO的recordcount不正確的時候,可以按F5,  Go to – Special – Last Cell. 看有多少行數據.

Excel 2003

image ADO Incorrect RecordCount 

Excel 2007 or later

image 3 ADO Incorrect RecordCount

確認行數錯誤的時候,利用下述Sub routine將無意義之數據清除

Sub deleteInvalidLines()
     ThisWorkbook.Sheets ("Mysheet")
                .UsedRange
                .Columns (1)
                .SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End Sub
article clipper remember ADO Incorrect RecordCount