Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Dim Map As Variant, x As Variant
Dim i As Long, j As Long, k As Long, n As Long, nRows As Long
Dim cel As Range, rg As Range
Dim ws1 As Worksheet, ws2 As Worksheet
With Worksheets("Mapping")
Set ws1 = Worksheets(.Range("A1").Value)
Set ws2 = Worksheets(.Range("B1").Value)
If Sh.Name <> ws1.Name And Sh.Name <> ws2.Name Then Exit Sub
Map = Range(.Cells(2, 1), .Cells(65536, 2).End(xlUp))
End With
nRows = UBound(Map)
Application.ScreenUpdating = False
Application.EnableEvents = False
On Error GoTo errhandler
For i = 1 To nRows
For j = 1 To 2
x = InStr(1, Map(i, j), ":")
If x = 0 Then
Map(i, j) = Range(Map(i, j)).Address
Else
Map(i, j) = Range(Left(Map(i, j), x - 1)).Address & ":" & Range(Mid(Map(i, j), x + 1)).Address
End If
Next j
Next i
For Each cel In Target
Select Case Sh.Name
Case ws1.Name
For i = 1 To nRows
If Map(i, 1) <> "" Then
Set rg = ws1.Range(Map(i, 1))
If Not Intersect(rg, cel) Is Nothing Then
j = cel.Row - rg.Row
k = cel.Column - rg.Column
cel.Copy ws2.Range(Map(i, 2)).Cells(1, 1).Offset(j, k)
Application.CutCopyMode = True
End If
End If
Next i
Case ws2.Name
For i = 1 To nRows
If Map(i, 2) <> "" Then
Set rg = ws2.Range(Map(i, 2))
If Not Intersect(rg, cel) Is Nothing Then
j = cel.Row - rg.Row
k = cel.Column - rg.Column
cel.Copy ws1.Range(Map(i, 1)).Cells(1, 1).Offset(j, k)
Application.CutCopyMode = True
End If
End If
Next i
End Select
Next cel
errhandler:
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
|