Excel VBA:如何使用* content *查找* second last *行?

时间:2016-11-07 16:20:30

标签: excel vba excel-vba row rows

假设列Exception raised in callable attribute "production_cost"; original exception was: 'function' object has no attribute 'getCheapest' 中有100行。其中A确实包含内容,第90行是100列(低于A)中所有单元格的总和,不包括100个空单元格。

现在,假设第二行最后一行包含内容是行9。在编写VBA代码时如何找到它?

我知道如何找到包含内容的 last 行。它的代码是:

95

如你所见,只是减去LastCellA = .Cells(.Rows.Count, "A").End(xlUp).Row 就无法完成这项工作。那么,解决方案是什么?

5 个答案:

答案 0 :(得分:1)

这将找到第二个非空单元格

LastCellA = .Cells(.Rows.Count, "A").End(xlUp).Row

SecondLastCellA = LastCellA - 1
Do While .Cells(SecondLastCellA, "A") = ""
    SecondLastCellA = SecondLastCellA - 1
Loop

答案 1 :(得分:0)

这是我将如何做到的:

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

通过传递工作表参考和搜索列的字母来调用函数,例如:

Debug.Print findSecondLastRow(ActiveSheet, "A")

答案 2 :(得分:0)

你可以试试这个

假设您对具有常量数字值的最后一个单元格感兴趣(即不是文本和/或公式)

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)

答案 3 :(得分:-1)

mybottom = .Cells(.Rows.Count, "A").End(xlUp).Row
lastcellA = .cells(mybottom -1,"A").end(xlup).row

答案 4 :(得分:-1)

试试这个

lr = .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row - 1, 1).End(xlUp).Row