vba - excel - if value = next row value then copy

2019-09-07 22:25发布

Good morning guys, I have a problem with the modify the data in a file. I'd like my script take as a reference the data in column H and go to act only if the data is equal to the data of the next row, copying the values of the column I and J of the second line and pasting them in the first free cell after the column J in the top row.

Now the file is organized so Now the file is organized so

I would like it to become so

I would like it to become so

the only code that I was able to write is this:

With ws1
For row = 2 To 1000

    If .Cells(8, row).Value Like .Cells(8, row + 1).Value Then

        .Cells(9 - 2, row).Value = .Cells(9, row + 1).Value

 End If
 Next
 End With

but obviously it is wrong and it does not minimally what I would ...

I'm really stuck .... help me please.

1条回答
【Aperson】
2楼-- · 2019-09-07 23:31

The below code has been tested and works on my sample data.

With ws1

    Dim lRow As Long
    lRow = .Range("H" & .Rows.Count).End(xlUp).Row

    Dim i As Long
    For i = lRow To 2 Step -1

        If .Range("H" & i) = .Range("H" & i - 1) Then

            .Range(.Range("I" & i), .Range("I" & i).End(xlToRight)).Copy _
                Destination:=.Range("H" & i - 1).End(xlToRight).Offset(, 1)

            .Range(.Range("I" & i), .Range("I" & i).End(xlToRight)).ClearContents

            'uncomment below line if you want to remove rows where data is copied up
            '.Range("H" & i).EntireRow.Delete

        End If

    Next

End With
查看更多
登录 后发表回答