Foreach over Excel单元格只返回运行中的第一行,但在单步执行该方法时正常工作

我使用Excel电子表格作为时间段logging的数据表。 结构是这样的:

ID Person Start End 1 Alan 5/1 5/3 2 Bobbi 5/3 5/4 3 Chuck 5/1 5/2 5 Eugenia 5/3 5/6 6 Chuck 5/10 5/12 

StartEnd被格式化为date字段。

我在VBA模块中编写了一个方法来查询这个表并返回一个给定的人的所有行,比如Chuck 。 在SQL中,这很容易( select fields from History where Person = something )。 我目前正在使用一个foreach循环,并testing人的价值。 我的循环如下所示:

 Public Sub UpdatePeriod(currentPeriod as timePeriod) Dim indexCell As Range Dim colPeriods As New Collection Dim priorPeriod As timePeriod For Each indexCell in ThisWorkbook.Worksheets("History").Range("A2:A" & Range("A" & Rows.Count).End(xlUp).Row).Cells If Not (indexCell Is Nothing) And IsNumeric(indexCell) = True Then Set priorPeriod = GetPeriodObject(indexCell) If (priorPeriod.Person = currentPeriod.Person) Then colPeriods.Add priorPeriod End If End If Next 'Do stuff with the entries in colPeriods.... End Sub 

我设置了电子表格,以便某个Worksheet_Change表的Worksheet_Change事件处理程序将一个timePeriod对象传递给此方法。 到目前为止,一切工作正常(虽然可能有更好的方法)。

当我在For Each之前testing这个方法时,这个循环只会遍历第2行(因为第1行包含头文件)。 但是当我在循环之前断开时,循环正确地遍历所有行。

如何改进这种方法来返回所有感兴趣的行?

(注意:该项目使用VBA作为原型,最终将成为具有合适数据库的正确应用程序,目的是使数据接口与应用程序实现完全一样。)

最可能的原因是你没有合格的第二个Range调用(或Rows )。 使用:

 For Each indexCell in ThisWorkbook.Worksheets("History").Range("A2:A" & ThisWorkbook.Worksheets("History").Range("A" & ThisWorkbook.Worksheets("History").Rows.Count).End(xlUp).Row).Cells 

使用工作表的variables将简化事情!

 With ThisWorkbook.Worksheets("History") For Each indexCell in .Range("A2:A" & .Range("A" & Rows.Count).End(xlUp).Row).Cells .... Next End With