首页 文章

使用Excel VBA查找最后一行

提问于
浏览
0

我有一个关于如何在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 回答

  • -1

    这个方法在我需要它的90%的时间里对我有用:

    Lastrow = Sheets("Annex 1A").UsedRange.SpecialCells(xlCellTypeLastCell).row
    
  • 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
    

相关问题