Originally Posted by
BenChod
That is one long piece of code to find the last row/col
Yes, but I put it in a function in my tool kit so I can just reuse it
I did have to make two changes since it seemed to give me an extra row and column if there was a shape like the picture below w/o the 2 changes
Capture.JPG
Option Explicit
Sub test()
MsgBox RealLastUsed(ActiveSheet).Address
End Sub
'Find the last used cell with a formula and value
'ref -- http://www.vbaexpress.com/kb/getarticle.php?kb_id=83
Function RealLastUsed(ws As Worksheet) As Range
Dim ColFormula As Range, ColValue As Range, RowFormula As Range, RowValue As Range
Dim LastRow As Long, LastCol As Long
Dim R As Long, C As Long
Dim oShape As Shape
With ws
'Search by Columns and Rows
On Error Resume Next
Set ColFormula = .Cells.Find(What:="*", After:=.Range("A1"), LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious)
Set ColValue = .Cells.Find(What:="*", After:=.Range("A1"), LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious)
Set RowFormula = .Cells.Find(What:="*", After:=.Range("A1"), LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
Set RowValue = .Cells.Find(What:="*", After:=.Range("A1"), LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
On Error GoTo 0
'Determine the last column
If ColFormula Is Nothing Then
LastCol = 0
Else
LastCol = ColFormula.Column
End If
If Not ColValue Is Nothing Then
LastCol = Application.WorksheetFunction.Max(LastCol, ColValue.Column)
End If
'Determine the last row
If RowFormula Is Nothing Then
LastRow = 0
Else
LastRow = RowFormula.Row
End If
If Not RowValue Is Nothing Then
LastRow = Application.WorksheetFunction.Max(LastRow, RowValue.Row)
End If
'Determine if any shapes are beyond the last row and last column
For Each oShape In .Shapes
R = 0
C = 0
On Error Resume Next
R = oShape.TopLeftCell.Row
C = oShape.TopLeftCell.Column
On Error GoTo 0
If R > 0 And C > 0 Then
Do Until .Cells(R, C).Top > oShape.Top + oShape.Height
R = R + 1
Loop
R = R - 1 ' get rid of extra row
If R > LastRow Then
LastRow = R
End If
Do Until .Cells(R, C).Left > oShape.Left + oShape.Width
C = C + 1
Loop
C = C - 1 ' get rid of extra col
If C > LastCol Then
LastCol = C
End If
End If
Next
Set RealLastUsed = .Cells(LastRow, LastCol)
End With
End Function