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



我正在使用Excel电子表格作为时间段历史记录的数据表。 结构是这样的:

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的格式设置为日期字段。

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

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事件处理程序将timePeriod对象传递给此方法。 到目前为止,一切正常(尽管可能有更好的方法(。

当我测试该方法而不在For Each之前中断时,循环只经过第 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

为工作表使用变量会简化事情!

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