VBA 镜像区域更新更新
VBA mirror areas update on change
我必须更新 Excel sheet 中的区域,如果其中任何一个区域的值发生变化,我需要更新这些区域。请参阅具有示例值的区域示例:
我试过的代码如下:
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 中编写时,代码会更新其他区域,但是当检测到更改时,会尝试更改初始区域。因此,代码陷入无限循环。
关于如何解决这个问题有什么想法吗?
我想要实现的是,无论用户更新什么部分,它都会被复制到另一个部分。
首先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
我必须更新 Excel sheet 中的区域,如果其中任何一个区域的值发生变化,我需要更新这些区域。请参阅具有示例值的区域示例:
我试过的代码如下:
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 中编写时,代码会更新其他区域,但是当检测到更改时,会尝试更改初始区域。因此,代码陷入无限循环。
关于如何解决这个问题有什么想法吗?
我想要实现的是,无论用户更新什么部分,它都会被复制到另一个部分。
首先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