获取最后一个非空单元格的行索引。

时间:2012-07-28 21:39:53

标签: excel vba excel-vba excel-2007

我是编码宏的新手,只是有一个简单的问题。我一直在尝试做的是在空单元格之前选择所有数据点,然后存储最后一个点的行索引。例如,在下面的代码中,我将选择第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

2 个答案:

答案 0 :(得分:1)

试试这个

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

答案 1 :(得分:0)

' 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
相关问题