Home > Software engineering >  Copy and paste a cell value on the last row of a column
Copy and paste a cell value on the last row of a column

Time:08-10

I'm facing a small issue, i need to write a code that copy a cell value and paste in in the last row found of a column (column L in my case), here is what i wrote:

lastRow = ThisWorkbook.Sheets("RecordAccordo").Range("L" & ThisWorkbook.Sheets("RecordAccordo").Rows.Count).End(xlUp).Row

        Range("B36").Copy
        
        ThisWorkbook.Sheets("RecordAccordo").Range("L2:L" & lastRow).PasteSpecial Paste:=xlPasteValues

My issue is that the value of cell B36 is pasted on all the column L rows while i need it only in the last row found

CodePudding user response:

Your error is basically that you are referencing the whole column when pasting the value: .Sheets("RecordAccordo").Range("L2:L" & lastRow).

Correct would be .Sheets("RecordAccordo").Range("L" & lastRow)

But I refactored your code a bit to be more precise and readable plus showing you that copy/paste is not necessary - as you can use the value properties of source and target range

Public Sub copyValue()

Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("RecordAccordo")

Dim cSource As Range
Set cSource = ws.Range("B36")

Dim lastRow As Long
With ws
    lastRow = .Range("L" & .Rows.Count).End(xlUp).Row
End With

Dim cTarget As Range
Set cTarget = ws.Range("L" & lastRow)

cTarget.Value = cSource.Value

End Sub
  • Related