6

I am writing a macro to iterate over some records and wanted to a for-loop to avoid any chance of infinite while looping like:

For i = 0 to COUNT
  **do stuff with START_CELL.Offset(i,0)
Next

I couldn't remember how to do a count of things from VBA so a search sent me here: Use VBA to Count Non Blank Cells in a Column. One suggestion was

n = Worksheets("Sheet1").Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count

This seemed over complicated, so I did some more digging and decided I was going to use:

COUNT = Application.WorksheetFunction.Count(COUNT_RANGE)

Another example on that page used Application.WorksheetFunction.CountA(), but still now I am concerned (paranoid) there is a reason I should avoid it. Are there any?

Thanks all.

4

1 回答 1

6

避免工作表函数的唯一原因是您担心与旧版本的 Excel 的向后兼容性。新版本的 Excel 通常会引入新的工作表函数。如果这些在您的用户版本的 Excel 中不可用,您将遇到困难。

除此之外,如果您知道这些功能在您的用户正在使用的版本上可用,那么它们通常非常有效并且通常比 VBA 中的等效功能更快,特别是如果它们避免循环遍历单元格,如评论中所述。

于 2013-08-29T21:58:47.847 回答