Write Excel macros to easily swap cell data

Source: Internet
Author: User
Tags count ranges

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.