Excel VBA: Get Last Cell Containing Data within Selected Range

后端 未结 3 553
清酒与你
清酒与你 2021-01-06 04:51

How do I use Excel VBA to get the last cell that contains data within a specific range, such as in columns A and B Range(\"A:B\")?

3条回答
  •  渐次进展
    2021-01-06 05:21

    using Find like below is useful as it

    • can find the last (or first) cell in a 2D range immediately
    • testing for Nothing identifies a blank range
    • will work on a range that may not be contiguous (ie a SpecialCells range)

    change "YourSheet" to the name of the sheet you are searching

    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
    

提交回复
热议问题