Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I copy a row of data, and paste it with an offset

I'm working on a Excel 2010 Sheet that has some doctors names and their adresses, but frequently there are 2 names that are identical but have diferent adresses. On this cases I would like to copy the adress info to the same row as the first name but wit h an offset of 4 collumns. Heres the code I came up with

Sub OraganizadorEndereços()

    ActiveCell.Select
    If ActiveCell.Value = ActiveCell.Offset(1, 0).Value _
    Then ActiveCell.Offset(1, 0).Activate: _
    Range(ActiveCell.Offset(0, 1), ActiveCell.Offset(0, 4)).Copy: _
    ActiveCell.Offset(-1, 0).Select: _
    ActiveCell.Offset(0, 5).Paste _
    Else ActiveCell.Offset(1, 0).Select

End Sub

But I get an error on the

ActiveCell.Offset(0, 5).Paste _
Else ActiveCell.Offset(1, 0).Select

Part of the code, saying that the obeject does not accept this property/method

And remember, I started programing in VBA today, so if you can answer with an explanation, I would appreciate.

like image 382
Pedro Avatar asked Feb 17 '23 01:02

Pedro


1 Answers

Try to rely less on activating and selecting cells - you can assign cells to a range variable to make things much easier. Also, you don't need to copy the cells (unless you also want to copy the formatting e.g. colours), use their .Value instead:

Sub OraganizadorEndereços()

Dim rngTest as Range 'Define rngTest variable as Range
Set rngTest = Activecell 'Set rngTest to be the ActiveCell
If rngTest.Value = rngTest.Offset(1, 0).Value Then 
    'Replace the .Value of the columns to right with the .Value of the row below
    Range(rngTest.Offset(0,5), rngTest.Offset(0,8).value = Range(rngTest.Offset(1, 1), rngTest.Offset(1, 4)).Value
Else 
    Set rngTest = rngTest.Offset(1,0) 'Set rngTest to be the next line down
End If

End Sub
like image 124
MattCrum Avatar answered Feb 24 '23 04:02

MattCrum