VBA镜像区域随更新而更新

时间:2018-04-04 12:42:24

标签: excel-vba onchange vba excel

如果具有相同值的任一区域发生更改,我需要Excel表单中的区域以供更新。请参阅具有示例值的区域示例:

enter image description here

我尝试过的代码如下:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim Area1 As Range
    Dim Area2 As Range

    ' The variable KeyCells contains the cells that will
    ' cause an alert when they are changed.
    Set Area1 = Range("B3:B9")
    Set Area2 = Range("D3:D9")

    If Not Application.Intersect(Area1, Range(Target.Address)) _
           Is Nothing Then
        Range("D" & Target.Row) = Target.Value
    End If

    If Not Application.Intersect(Area2, Range(Target.Address)) _
           Is Nothing Then
        Range("B" & Target.Row) = Target.Value
    End If
End Sub

问题是我收到了错误。我相信因为当我在区域1或2中写入时,代码会更新其他区域,但是当检测到更改时,则尝试更改初始区域。因此,代码进入了无限循环。

关于如何对此问题进行排序的任何想法?

我想要实现的是,除了用户更新的部分,它将被复制到另一部分。

1 个答案:

答案 0 :(得分:2)

首先Range(Target.Address)没有多大意义Target已经是一个范围,因此您将范围转换为范围内的地址。只需直接使用Target

此处的问题是,如果您更改Worksheet_Change事件中的单元格,则会触发另一个Worksheet_Change事件,从而触发另一个事件...

因此,您需要在更改前Application.EnableEvents = False和之后Application.EnableEvents = True

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim Area1 As Range
    Dim Area2 As Range

    ' The variable KeyCells contains the cells that will
    ' cause an alert when they are changed.
    Set Area1 = Range("B3:B9")
    Set Area2 = Range("D3:D9")

    Application.EnableEvents = False

    If Not Application.Intersect(Area1, Target) Is Nothing Then
        Range("D" & Target.Row) = Target.Value
    End If

    If Not Application.Intersect(Area2, Target) Is Nothing Then
        Range("B" & Target.Row) = Target.Value
    End If

    Application.EnableEvents = True
End Sub