How do I implement data exchange between two cell ranges in an Excel table? Usually we use the Cut-and-paste method to complete, but this method is more cumbersome, if the data area is more prone to error. 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 &" Do you want to 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 "Selected two data regions of different sizes!" Please confirm your choice again! " End If Else MsgBox "Please hold down the CTRL key to select two data areas to be exchanged!" " |
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.