When a cell value changes, copy the column from where the cell value changed to another sheet at the same range

百般思念 提交于 2019-12-13 05:06:25

问题


For example, if in the range of A:A only cell A8 change then copy D4:D8 and paste it as value in sheet "ADP" at the same place i.e. D4:D8.

For that I have tried the following macro

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.range = "A:A" Then
        Call copy_paste_as_value
    End If
End Sub


Sub copy_paste_as_value()
    Range("d4").Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy

    Sheets("ADP").Activate
    Range("B4").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Range("C4").Select
    Application.CutCopyMode = False
End Sub

I want to copy only that data against which cell value changes, but it copies the whole table to another sheet.

main issue for me is to figure out which cell changed and copy data from that column only from which cell value changed.

here, it's to be noted that data should be copied only if there is change in range A:A, if change in any other cell than copy paste not required.

any help will be appriciated. thank you.


回答1:


You could try:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim wsSou As Worksheet, wsDes As Worksheet

    'Set the worksheets to avoid conflicts
    Set wsSou = Target.Worksheet
    Set wsDes = ThisWorkbook.Worksheets("ADP")

    If Not Intersect(Target, Range("A:A")) Is Nothing And Target.Count = 1 Then

        wsDes.Range(wsDes.Cells(Target.Row, 4), wsDes.Cells(Target.Row, 9)).Value = wsSou.Range(wsSou.Cells(Target.Row, 4), wsSou.Cells(Target.Row, 9)).Value

    End If

End Sub



回答2:


Assuming the relative range is consistent, try this

Private Sub Worksheet_Change(ByVal Target As Range)

Dim r As Range

If Target.Column = 1 And Target.Row > 4 Then
    Set r = Target.Offset(-4, 3).Resize(5)
    Worksheets("ADP").Range(r.Address).Value = r.Value
End If

End Sub


来源:https://stackoverflow.com/questions/56458158/when-a-cell-value-changes-copy-the-column-from-where-the-cell-value-changed-to

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