使用Excel VBA查找最后一行

时间:2016-05-09 03:54:10

标签: excel vba excel-vba

我有一个关于如何在excel vba中查找最后一行的查询。我目前正在开展一个项目,要求我找到这个名为Annex 1A的特定工作表的最后一行。

工作表的剪辑图片如下所示:

Click Here For Image

例如,从上图中,Row 32Row 33包含空值,我想得出正在使用的行总数。

我尝试了以下方法:

方法1

LastRow = Sheets("Annex 1A").Cells.Find(What:="*", _
                  After:=Sheets("Annex 1A").Range("B1"), _
                  Lookat:=xlPart, _
                  LookIn:=xlFormulas, _
                  SearchOrder:=xlByRows, _
                  SearchDirection:=xlPrevious, _
                  MatchCase:=False).Row

方法2

  LastRow = Sheets("Annex 1A").Range("B" & Sheets("Annex1A").Rows.Count).End(xlUp).Row

LastRow值始终返回31而不是33。有没有其他方法可以推导出33的价值?

2 个答案:

答案 0 :(得分:0)

这种方法在我需要的时候有90%的时间对我有用:

Lastrow = Sheets("Annex 1A").UsedRange.SpecialCells(xlCellTypeLastCell).row

答案 1 :(得分:0)

我知道你已经接受了答案,但这可能对其他人有用。

UsedRange经常被避开,因为它可能不可靠。但是,在这种情况下,它确实有一个地方,可以帮你解决问题。

但是,如果您希望重新获得UsedRange的完全控制权,那么将UsedRange与某些定制单元格检查相结合的方法可能就是答案。在您的情况下,可能是一个查找非空单元格或带阴影的单元格的示例。

Public Function BespokeFindLastRow() As Long
    Dim rng As Range
    Dim i As Long

    'Use the intersect function to find column B
    'as column references of UsedRange are relative
    'so if nothing is in column "A", then
    'column(1) or ("A") in your UsedRange would
    'actually be column "B".
    With ThisWorkbook.Worksheets("Sheet1")
        Set rng = Intersect(.UsedRange, .Columns("B"))
    End With

    'Return -1 if no cells are found
    If rng Is Nothing Then
        BespokeFindLastRow = -1
        Exit Function
    End If

    'Loop backwards through the cells in the column range
    'to find either a non-empty cell or a coloured cell.
    For i = rng.Cells.Count To 1 Step -1
        With rng.Cells
            If Not IsEmpty(.Item(i)) Or .Interior.ColorIndex <> xlNone Then
                BespokeFindLastRow = .Row
                Exit Function
            End If
        End With
    Next

    'Nothing was found in the column so return -1
    BespokeFindLastRow = -1
End Function
相关问题