【问题标题】:Finding Last Row using Excel VBA使用 Excel VBA 查找最后一行
【发布时间】:2016-05-09 03:54:10
【问题描述】:

我询问如何在 excel vba 中找到最后一行。我目前正在开展一个项目,该项目需要我找到名为 Annex 1A 的特定工作表的最后一行。

工作表的截图如下所示:

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

我已经尝试过以下方法:

方法一

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

方法二

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

LastRow 值将始终返回 31 而不是 33。我还有其他方法可以得出33 的值吗?

【问题讨论】:

标签: vba excel


【解决方案1】:

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

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

【讨论】:

  • 谢谢@gizlmeier!我终于通过使用你的方法将 33 作为一个值推导出来了 :) !
【解决方案2】:

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

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

【讨论】:

  • 是否也可以修改这个sub以获得lastRow而不指定列?我喜欢那个代码,因为如果列中没有值,它会返回“0”。
  • @smartini,我们倾向于不在同一个问题中回答扩展问题,以便以后发现这个问题的人看到一个问题和答案。如果您发布新问题,我或其他人会很乐意回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多