Excel VBA:获取最后一个单元格包含选定范围内的数据
如何使用Excel VBA获取包含特定范围内的数据的最后一个单元格,如列A和B Range("A:B")
?
使用下面的Find
是有用的,因为它
- 可以立即find2D范围内的最后(或第一个)单元格
-
Nothing
testing标识一个空白范围 - 将工作在可能不连续的范围(即
SpecialCells
范围)
将"YourSheet"
更改为您正在search的工作表的名称
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
你可以尝试几种方法:
使用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
使用SpecialCells
Dim WS As Worksheet Dim LastCell As Range Set LastCell = Range("A:B").SpecialCells(xlCellTypeLastCell)
后者有时可能会非常棘手,可能无法按照您的要求工作。
更多提示
你也可以看看Chip Pearson的关于这个问题的网页
对于可以使用的variablesselect
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