2016-11-07 670 views
1

假設列A中有100行。 90其中包含內容,行100是列A(低於100)中所有單元格的總和,不包括9空單元格。Excel VBA:如何找到帶*內容*的*倒數第二*行?

現在,假設最後一行與內容95行。如何在編寫VBA代碼時找到它?

我知道如何找到最後行的內容。它的代碼是:

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

只是減去1不會做的工作,因爲你看到的。那麼,解決方案是什麼?

回答

1

這將找到的倒數第二個非空單元格

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

SecondLastCellA = LastCellA - 1 
Do While .Cells(SecondLastCellA, "A") = "" 
    SecondLastCellA = SecondLastCellA - 1 
Loop 
-1
mybottom = .Cells(.Rows.Count, "A").End(xlUp).Row 
lastcellA = .cells(mybottom -1,"A").end(xlup).row 
+0

如果沒有空白,這不起作用。在我的測試工作表中,我用數字1-10填充1-10行。你可以很容易找到第10行,但下一個找到第1行,因爲沒有休息。 – tjb1

-1

試試這個

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

與其他答案相同的問題,除非數據中斷,否則返回首行數據。 – tjb1

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 

調用函數通過作爲參數傳遞工作表參考和le搜索欄,例如:

Debug.Print findSecondLastRow(ActiveSheet, "A") 
0

你可以試試這個

假設你是一個數字常量值感興趣的最後一個單元格的tter(即沒有文字或沒有公式)

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)