Thread: Last cell
View Single Post
  #8   Report Post  
Posted to microsoft.public.excel.programming
Leo Heuser[_3_] Leo Heuser[_3_] is offline
external usenet poster
 
Posts: 109
Default Last cell

Thanks, Paul.
Please see my answer to Dave Peterson's posting

Regards
LeoH


"Paulw2k" skrev i en meddelelse
...
Hi,

The last cell may not be the one you expect as XL remembers every used

cell
so that
the UsedRange may be far larger than you want to print.

The function below returns the 'actual' last cell, given the existing data
spread.

So,

Sub YourProcedure()
.....
Dim rngLastCell as Range
dim sPrintAdrs as String
.....

set rngLastCell = RealLastCell(ActiveSheet)

sPrintAdrs = Range("A1:" & rngLastCell.Address)
ActiveSheet.PageSetup.PrintArea = sPrintAdrs

.....

End Sub


Function RealLastCell(ws As Worksheet) As Range
Dim LastRow As Long, LastCol As Integer

' Error-handling is here in case there is not any
' data in the worksheet

On Error Resume Next

With ws
' Find the last real row
LastRow = .Cells.Find(What:="*", _
SearchDirection:=xlPrevious, _
SearchOrder:=xlByRows).Row
' Find the last real column
LastCol = .Cells.Find(What:="*", _
SearchDirection:=xlPrevious, _
SearchOrder:=xlByColumns).Column
End With

' Finally, initialize a Range object variable for
' the last populated row.
If LastCol = 0 And LastRow = 0 Then
Set RealLastCell = ws.Cells(1, 1)
Else
Set RealLastCell = ws.Cells(LastRow, LastCol)
End If
End Function



Regards

Paul