How do I implement data exchange between two cell ranges in an Excel table? Usually we use the Cut-and-paste method to do this, but this method is cumbersome, and error prone if the data area is larger. Let's try to write a "macro" that can implement that functionality.
On the Tools menu, open macros, select Record new macros, and in the Personal Macro Workbook (Personal.xls), create a macro called Exchange that has the following code:
Code:
' Determine if the user has selected two cells or ranges of cells
If Selection.Areas.Count = 2 Then
Set XR = selection.areas (1)
Set YR = Selection.areas (2)
' Determine if the selection overlaps
If not Intersect (XR, YR) are nothing Then
result = MsgBox ("Select area has overlap!") data for overlapping areas after swapping will be partially overwritten! "& VbCrLf &" Continue? ", vbYesNo)
If result = vbno Then Exit Sub
End If
If XR. Rows.Count = YR. Rows.Count and XR. Columns.count = YR. Columns.count Then
' Swap constituencies
SZ1 = XR. Formula
SZ2 = YR. Formula
XR = SZ2
YR = SZ1
Else
MsgBox "Select two data regions of different sizes!" Please confirm your choice again! "
End If
Else
MsgBox "Please hold down the CTRL key and select two data areas to swap!"
Customize a toolbar button and assign the created macro to the button (figure). If the range size (number of cells) of the selected two cells is different or the selected data is less than 2, the system will give a corresponding error prompt.
Exchange with macros