检查单元格是否是Excel范围的最后一个单元格

我正在循环MyRange范围。 我需要找出是否CellMyRange的最后一个单元格。

 For Each Cell In MyRange.Cells If Cell = ' What should I write here? 'Do some stuff End If Next Cell 

我试过这个:

 If Cell = MyRange.Cells(0, MyRange.Count) Then 

但它给错误。

我该怎么办呢?

我喜欢一些其他的答案,但最短的方式可能如下:

 If Cell.Address = myRange.Cells(myRange.Cells.Count).Address Then 

重要说明如果myRange是单元格的连续范围,则上述解决scheme将起作用。

如果你的区域不是连续使用@Doug Glancy的逻辑,那么这个逻辑可以表示如下:

 If Cell.Address = myRange.Areas(myRange.Areas.Count).Cells(myRange.Areas(myRange.Areas.Count).Cells.Count).Address Then 

请! 如果有人想奖励这个答案,请用@Doug Glancy答案自动完成(谁是第一个)。

你的回答很好,但这是一个有趣的问题。 这是预先弄清楚的方法:

 Sub test() Dim MyRange As Excel.Range Dim cell As Excel.Range Dim LastCell As Excel.Range Set MyRange = Selection Set LastCell = MyRange.Areas(MyRange.Areas.Count).Cells(MyRange.Areas(MyRange.Areas.Count).Cells.Count) For Each cell In MyRange If cell.Address = LastCell.Address Then MsgBox cell.Address Exit For End If Next cell End Sub 

请注意,在我们的两种方法中,如果有多个区域,“最后一个单元”可能不是最底部或最右侧的单元。 例如,select单元格J10:J20,然后selectE5:E10并运行以上。 结果将是E10,因为它是最后select的。

AFAIK,您可以通过索引访问单元格。
尝试用For Each loopreplaceFor Each loop for loop

我觉得像这样的东西应该工作(未经testing):

 Dim rng As Integer = myrange.Cells.Count For i As Integer = 0 To rng - 1 '...do something If i = rng Then End If Next 

我做到了这一点,以达成结论

 Dim i As Integer: i = 1 For Each Cell In MyRange.Cells If i = MyRange.Cells.Count Then 'Do if stuff using Cell Else 'Do else stuff using Cell End If i = i + 1 Next Cell 

要检查2个范围是否相同,可以使用相交方法 (如果它们不相交,则它们不相同)。

 Sub lastCellInForEach() Dim cell As Range, myrange As Range Set myrange = ActiveSheet.Range("A1:C1000") For Each cell In myrange.Cells 'using Intersect to check if cell is the last cell in the range If Not Intersect(cell, myrange(myrange.cells.count)) Is Nothing Then debug.print cell.address End If Next cell End Sub