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

白昼怎懂夜的黑 提交于 2019-12-12 12:27:18

问题


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.


回答1:


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



回答2:


Try below code :

Sub OraganizadorEndereços()

    Dim rng As Range
    Dim offsetRng As Range

    Set rng = ActiveCell
    rng.Select

    Set offsetRng = rng.Offset(1, 0)

    If rng = offsetRng Then
        offsetRng.Offset(0, 1).Resize(, 4).Copy offsetRng.Offset(0, 5)
        rng.Offset(1, 0).Activate
    Else
        rng.Offset(1, 0).Select
    End If

End Sub


来源:https://stackoverflow.com/questions/15573778/how-can-i-copy-a-row-of-data-and-paste-it-with-an-offset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!