Reputation: 125
I found the below code from Here.
With Sheets("Sheet1")
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
lastrow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Else
lastrow = 1
End If
End With
My reputation is too low so I can't comment and ask there. What or where is the output? I'm not able to bind the code in?
Upvotes: 1
Views: 1708
Reputation:
That code gives you the last row of any column within the worksheet's Worksheet.UsedRange property with a value in it; not the last cell with a value in one particular column. The two may be the same thing but are not guaranteed to be the same.
To get the row with the last value in a particular column (e.g. column B) then this would be more appropriate.
With Sheets("Sheet1")
If Application.WorksheetFunction.CountA(.Columns(2)) <> 0 Then
lastrow = .Cells(rows.Count, "B").End(xlUp).Row
Else
lastrow = 1
End If
End With
To use this lastrow to set a value in the next cell (first blank), add 1 and use it in the row_num parameter of a Range.Cells property.
With Sheets("Sheet1")
If Application.WorksheetFunction.CountA(.Columns(2)) <> 0 Then
lastrow = .Cells(rows.Count, "B").End(xlUp).Row
Else
lastrow = 1
End If
.Cells(lastrow + 1, "B") = "my new value"
End With
Upvotes: 3