获取最后一个非空白单元格的行索引。
问题描述:
我是新来的编码宏,只是有一个快速的问题。我一直在试图做的是在空单元格之前选择所有数据点,然后存储最后一点的行索引。例如,在下面的代码我想选择行1-4和将被存储在行指数为4。我有此代码到目前为止它选择数据点:获取最后一个非空白单元格的行索引。
Cells(2, 2).Select
Range(Selection, Selection.End(xlDown)).Select
我只需要存储的最后一行索引。示例数据:
1. 342
2. 342
3. 324
4. 234
5. <This would be an empty cell>
6. 43242
7. 342
8. 32423
9. 4324
答
' column = whatever column you're working with
For evalRows = 1 to Range(Selection, Selection.End(xlDown)).Row
If IsEmpty(Cells(evalRows, column).Value) Then
' you can only refer to the previous row if you're not on the first row
If evalRows = 1 then
' do nothing
Else
' refer to previous row
lastUsefulRow = Offset(evalRows - 1, column).Row
End If
End If
Next
答
试试这个
LastRow = Cells(2, 2).End(xlDown).Row
如果你在选择范围的意图,使用
LastRow = Selection.Row + Selection.Rows.Count - 1
虽然我建议不要选择范围。使用这个代替
Dim rng As Range
Set rng = Range(Cells(2, 2), Cells(2, 2).End(xlDown))
LastRow = rng.Row + rng.Rows.Count - 1