I have to areas in an Excel sheet that I need for them to get updated if there is a change in either of the area with the same value. See example of areas with example values:
The code that I tried is as follows:
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
The problem is that I’m getting an error. I believe because when I write in Area 1 or 2 the code update the other area, but as a change is detected, then tries to change the initial area. Therefore, the code is getting in an endless loop.
Any ideas on how I can sort this issue?
What I’m trying to achieve is that what ever section the user updates, it will be replicated in the other.
First of all Range(Target.Address)
doesn’t make much sense Target
is already a range so you convert a range into an address into a range. Just use Target
directly.
The issue here is that if you change a cell within Worksheet_Change
event this triggers another Worksheet_Change
event, which triggers another and …
So you need to Application.EnableEvents = False
before the change and Application.EnableEvents = True
afterwards.
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
Tags: date, excel-vbaexcel, vba