Find Last cell from Range VBA

2019-05-25 03:42发布

How to find location of last cell from defined Range? Cell does not have to contain any data but must be most right and most down located cell from certain Range.

Set rngOrigin = wksOrigin.Cells(IntFirstRow, IntFirstColumn).CurrentRegion

I wish to receive

Cells(i,j)

标签: vba range cell
7条回答
我想做一个坏孩纸
2楼-- · 2019-05-25 03:56

The answers given by others mostly work, but not if the region is a union of non-contiguous cells. Here is a version that works consistently for single and multi-area regions, contiguous and non-contiguous.

Function LastCellOfRange(rng As Excel.Range) As Excel.Range
  Dim area As Excel.Range
  Dim rowNum As Long
  Dim maxRow As Long
  Dim colNum As Long
  Dim maxCol As Long
  Dim areaIdx As Integer

  Set LastCellOfRange = Nothing

  maxRow = 0
  maxCol = 0
  For areaIdx = 1 To rng.Areas.Count
    Set area = rng.Areas(areaIdx)
    rowNum = area.Cells(area.Cells.Count).row
    If (rowNum > maxRow) Then
      maxRow = rowNum
    End If
    colNum = area.Cells(area.Cells.Count).Column
    If (colNum > maxCol) Then
      maxCol = colNum
    End If
  Next areaIdx

  Set LastCellOfRange = rng.Worksheet.Cells(maxRow, maxCol)
  Set area = Nothing
End Function
查看更多
贼婆χ
3楼-- · 2019-05-25 03:57

Perhaps this is what you want:

Dim rngLastCell As Range
Set rngLastCell = rngOrigin(rngOrigin.Count)
查看更多
三岁会撩人
4楼-- · 2019-05-25 03:58

In your case, since you want to find the cell to the most right and down in your wksOrigin (defined as Worksheet), you could use the SpecialCells(xlCellTypeLastCell) to get the last cell Row and Column.

i = wksOrigin.Cells.SpecialCells(xlCellTypeLastCell).Row ' <-- get last row number
j = wksOrigin.Cells.SpecialCells(xlCellTypeLastCell).Column ' <-- get last column number

If you want to debug your result, you can add:

MsgBox "Last row at " & i & ", last column at " & j
查看更多
三岁会撩人
5楼-- · 2019-05-25 04:00

I handled it in below code but your remarks were helpful. Thank you.

intLastRow = rngOrigin.Cells(1, 1).Row + rngOrigin.Rows.Count - 1
intLastCol = rngOrigin.Cells(1, 1).Column + rngOrigin.Columns.Count - 1
查看更多
手持菜刀,她持情操
6楼-- · 2019-05-25 04:05

try the following

rngOrigin.End(xlDown).End(xlRight)

or you could use the CurrentRegion and count the rows and columns and use Offset

查看更多
啃猪蹄的小仙女
7楼-- · 2019-05-25 04:07

maybe you're after this:

'absolute indexes from cell A1
With rngOrigin
    i = .Rows(.Rows.count).row
    j = .Columns(.Columns.count).Column
End With

'relative indexes from rngOrigin upleftmost cell
With rngOrigin
    i = .Rows(.Rows.count).row - .Rows(1).row + 1
    j = .Columns(.Columns.count).Column - .Columns(1).Column + 1
End With
查看更多
登录 后发表回答