Excel VBA:查找最后一行

时间:2018-08-15 19:14:34

标签: excel vba excel-vba

我正在尝试为每一列查找一组数字的最后一行,但是似乎我的代码使用的是与前一列最后一行相同的最后一行。

这是第一列的代码:

Dim WorkRng As Range
xTitleId = "Select Total Sales cell"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
WorkRng.Select
Selection.Copy
Range("A65") = "Total Sales"
Range("A66").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Set WorkRng = Range("A66")

这是相邻列的代码:

Dim WorkRng2 As Range
xTitleId2 = "Select Collected Range"
Set WorkRng2 = Application.Selection
Set WorkRng2 = Application.InputBox("Range", xTitleId2, WorkRng2.Address, Type:=8)
WorkRng2.Select
Selection.Copy
Range("B65") = "Collected Range"
Range("B66").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Range("B66:B100").Select
Selection.SpecialCells(xlCellTypeBlanks).Select
Selection.Delete Shift:=xlUp
Range("B66").Select
Dim LastRow2 As Long
LastRow2 = Cells(Rows.Count, 1).End(xlUp).Row
Range("B" & LastRow2).Offset(1, 0).Formula = "=SUM(B66:B" & LastRow2 & ")"
Range("B" & LastRow2).Offset(1, 0).Select
Set WorkRng2 = Range("B" & LastRow2).Offset(1, 0)

它总是说LastRow2是66,但是我希望它是动态的并且独立于第一列的最后一行。

非常感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您可以添加如下所示的VBA功能:

    Function GetLastRow(wsTarget As Worksheet, iCol)
    'Gets the last non-blank cell
    Dim lrow As Long, Max_Row

    Max_Row = 1048576
        On Error GoTo SmallFile

    TryAgain:
        With wsTarget
            lrow = .Cells(Max_Row, iCol).End(xlUp).Row
        End With

        GetLastRow = lrow

        Exit Function
    SmallFile:
        Max_Row = 65536
        On Error GoTo 0
        GoTo TryAgain

    End Function

然后,指定要使用的工作表和列号。即GetLastRow(worksheets(“ Sheet1”),1)将返回Sheet1标签中A列的最后一行。