我正在循环 MyRange
范围。我需要找出 Cell
是 MyRange
的最后一个单元格.
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
但它给出了错误。
我该怎么办?
最佳答案
您的答案很好,但这是一个有趣的问题。这是一种预先弄清楚的方法:
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
请注意,在我们的两种方法中,如果有多个区域,“最后一个单元格”可能不是最底部或最右侧的单元格。例如选择单元格 J10:J20 然后 E5:E10 并运行上面的。结果将是 E10,因为它是最后选择的。
关于vba - 检查单元格是否是 Excel 范围的最后一个单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16454103/