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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11704860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 17:05:51  来源:igfitidea点击:

Get row index of last non-blank cell.

excelvbaexcel-vbaexcel-2007

提问by user1560170

I'm new to coding macros and just had a quick question. What I have been trying to do is select all the data points before an empty cell, then store the row index of the last point. For example, in the code below I would select rows 1-4 and the row index that would be stored is 4. I have this code so far which selects the data points:

我是编码宏的新手,只是有一个简单的问题。我一直在尝试做的是选择空单元格之前的所有数据点,然后存储最后一个点的行索引。例如,在下面的代码中,我将选择第 1-4 行,并且将存储的行索引为 4。到目前为止,我有这个选择数据点的代码:

Cells(2, 2).Select
Range(Selection, Selection.End(xlDown)).Select 

I just need to store the last row index. Example data:

我只需要存储最后一行索引。示例数据:

1. 342
2. 342
3. 324
4. 234
5. <This would be an empty cell>
6. 43242
7. 342
8. 32423
9. 4324

回答by chris neilsen

Try this

尝试这个

LastRow = Cells(2, 2).End(xlDown).Row

If you are intent on Selecting the range, use

如果您打算选择范围,请使用

LastRow = Selection.Row + Selection.Rows.Count - 1

Although I would advise against Selecting ranges. Use this instead

虽然我建议不要选择范围。改用这个

Dim rng As Range
Set rng = Range(Cells(2, 2), Cells(2, 2).End(xlDown))
LastRow = rng.Row + rng.Rows.Count - 1

回答by Imaginativeone

' 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