Excel VBA:如何find*内容*的第二个*行?
假设A
列有100
行。 90
包含内容, 100
行是A
列中所有单元格的总和(低于100
),不包括9
空单元格。
现在,假设包含内容的倒数第二行是第95
行。 如何在编写VBA代码时find它?
我知道如何find内容的最后一行。 它的代码是:
LastCellA = .Cells(.Rows.Count, "A").End(xlUp).Row
正如你所看到的,仅仅减去1
就不能完成这项工作。 那么,解决scheme是什么?
这将find倒数第二个非空单元格
LastCellA = .Cells(.Rows.Count, "A").End(xlUp).Row SecondLastCellA = LastCellA - 1 Do While .Cells(SecondLastCellA, "A") = "" SecondLastCellA = SecondLastCellA - 1 Loop
以下是我将如何做到这一点:
Function findSecondLastRow(sht As Excel.Worksheet, colLetter As String) As Long Dim LastCell As Long, SecondLastCell As Long With sht.Columns(colLetter) LastCell = .Range(colLetter & .Rows.Count).End(xlUp).Row If .Range(colLetter & LastCell - 1) = vbNullString Then SecondLastCell = .Range(colLetter & LastCell).End(xlUp).Row Else SecondLastCell = LastCell - 1 End If End With findSecondLastRow = SecondLastCell End Function
通过作为parameter passing表单引用和search列的字母来调用函数,例如:
Debug.Print findSecondLastRow(ActiveSheet, "A")
你可以试试这个
假设你对最后一个具有常数值的单元格感兴趣(即不是文本和或不是公式)
Function MyLastCellRow(ws As Worksheet, colIndex As Long) As Long With ws.Columns(colIndex).SpecialCells(xlCellTypeConstants, xlNumbers) With .Areas(.Areas.Count) MyLastCellRow = .cells(.Rows.Count).Row End With End With End Function
如果你对最后一个具有常数值的单元格(即文本和/或数字,而不是来自公式) , xlNumbers
从SpecialCells(xlCellTypeConstants, xlNumbers)
mybottom = .Cells(.Rows.Count, "A").End(xlUp).Row lastcellA = .cells(mybottom -1,"A").end(xlup).row
尝试这个
lr = .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row - 1, 1).End(xlUp).Row