Wiser Osprey
Wiser Osprey

Reputation: 1

Select last row of last column

I am trying to select the last row of the last column in my worksheet.

Sub Paste2()
'
' Paste2 Macro
'

'
   Sheets("Macro").Select
   a = Range("B1")
   Sheets("Sheet1").Select
   ActiveSheet.Cells(2, a).End(x1Down).Offset(1, 0).Select
End Sub

the variable "a" is linked to a CountA Function on a seprate sheet counting the rows with non-empty cells.

When I run the macro it comes up with a Runtime error 1004 Application-defined or object-defined error.

How do I make this work?

Upvotes: 0

Views: 171

Answers (2)

Jur Pertin
Jur Pertin

Reputation: 564

Try this one:

Sub pfindLastNonEmptyCell()

Dim rngRange                As Range
Dim wksWorksheet            As Worksheet

'Set 'Sheet1' worksheet
Set wksWorksheet = Worksheets("Sheet1")


With wksWorksheet
    'Check for last non-empty cell
    Set rngRange = .Cells.Find("*", .Cells(1, 1), xlFormulas, xlWhole, xlByRows, xlPrevious)
End With

If Not rngRange Is Nothing Then
    'if found then activate the worksheet and select last non-empty cell
    wksWorksheet.Activate
    wksWorksheet.Cells(rngRange.Row, rngRange.Column).Select
Else
    'if not found gives message
    MsgBox "No Data in " & wksWorksheet.Name, vbCritical + vbInformation, "Error"
End If

End Sub

Upvotes: 0

anefeletos
anefeletos

Reputation: 702

Two mistakes:

Mistake 1:ActiveSheet.Cells(2, 1)

Mistake 2:xlDown, not x1Down!

Upvotes: 1

Related Questions