【问题标题】:Excel VBA: Get Last Cell Containing Data within Selected RangeExcel VBA:获取包含所选范围内数据的最后一个单元格
【发布时间】:2015-12-22 09:05:56
【问题描述】:

如何使用 Excel VBA 获取包含特定范围内数据的最后一个单元格,例如列 A 和 B Range("A:B")

【问题讨论】:

标签: vba excel


【解决方案1】:

像下面这样使用Find很有用

  • 可以立即找到二维范围内的最后一个(或第一个)单元格
  • 测试Nothing 识别出一个空白范围
  • 适用于可能不连续的范围(即SpecialCells 范围)

"YourSheet" 更改为您正在搜索的工作表的名称

Sub Method2()
    Dim ws As Worksheet
    Dim rng1 As Range
    Set ws = Sheets("YourSheet")
    Set rng1 = ws.Columns("A:B").Find("*", ws.[a1], xlValues, , xlByRows, xlPrevious)
    If Not rng1 Is Nothing Then
        MsgBox "last cell is " & rng1.Address(0, 0)
    Else
        MsgBox ws.Name & " columns A:B are empty", vbCritical
    End If
End Sub

【讨论】:

  • Find 确实也值得注意,即使这不是我最喜欢的方式:)
  • 对于更多一列/行 - 恕我直言,查找是最好的方法。 :) +1
【解决方案2】:

你可以尝试几种方法:

使用 xlUp

Dim WS As Worksheet
Dim LastCellA As Range, LastCellB As Range
Dim LastCellRowNumber As Long

Set WS = Worksheets("Sheet1")
With WS
    Set LastCellA = .Cells(.Rows.Count, "A").End(xlUp)
    Set LastCellB = .Cells(.Rows.Count, "B").End(xlUp)
    LastCellRowNumber = Application.WorksheetFunction.Max(LastCellA.Row, LastCellB.Row)
End With

使用特殊单元

Dim WS As Worksheet
Dim LastCell As Range
Set LastCell = Range("A:B").SpecialCells(xlCellTypeLastCell)

后者有时会很棘手,可能无法按您的意愿工作。

更多提示

你也可以看看Chip Pearson's page about this issue

【讨论】:

    【解决方案3】:

    对于变量选择,您可以使用

    Sub test()
        Dim arrArray As Variant
        Dim iAct As Integer
        Dim iHighest As Integer
        arrArray = Split(Selection.Address(1, 1, xlR1C1), ":")
        For Count = Right(arrArray(0), 1) To Right(arrArray(1), 1)
            iAct = ActiveSheet.Cells(Rows.Count, Count).End(xlUp).Row
            If iAct > iHighest Then iHighest = iAct
        Next Count
        MsgBox iHighest
    End Sub
    

    【讨论】:

    • 对于 Range("A:B") 只需替换 Selection
    • 抱歉,循环查找最后一个单元格,恕我直言,只是浪费时间和资源。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 2019-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-28
    相关资源
    最近更新 更多