Pinterest Pixel

How to Swap Values Using Macros in Excel

Have you ever wanted to try to swap values from one cell to another? It is possible... read more

Download Excel Workbook
Bryan
Posted on

Overview

Have you ever wanted to try to swap values from one cell to another? It is possible using Macros in Excel!

Plus you also get to learn some programming along the way, how cool is that?

Make sure your Excel has the Developer Tab enabled following this tutorial.

Here are the 2 values that we want to swap:

How to Swap Values Using Macros in Excel

I will show you step by step, on how we can swap values!

I explain how you can do this below:

How to Swap Values Using Macros in Excel | MyExcelOnline

Download excel workbookHow-to-Swap-Values-Using-Macros-in-Excel.xlsm

STEP 1: Go to Developer > Insert > ActiveX Controls > Button

How to Swap Values Using Macros in Excel

Drag anywhere in the Excel spreadsheet to create your Button!

How to Swap Values Using Macros in Excel

 

STEP 2: Right click on your new button and select View Code.

How to Swap Values Using Macros in Excel

 

STEP 3: Type in this code:

Dim container As Double

container = Range(“A8”).Value
Range(“A8”).Value = Range(“B8”).Value
Range(“B8”).Value = container

How to Swap Values Using Macros in Excel

Let us go through each line step by step:

Dim container As Double

This creates a new variable named container wherein we can store a numerical value inside. The double type means it can have a numerical value.

See also  How to Autofit Columns Using Macros in Excel

container = Range(“A8”).Value

Now we are getting the first value in Cell A8 and storing it into our container variable.

Range(“A8”).Value = Range(“B8”).Value

We will now copy the content of Cell B8 and paste it into Cell A8. First step done! So far both will have the value 500 in our example.

Range(“B8”).Value = container

Now the last step! Copy the content of the container variable into Cell B8. The swap is now complete!

 

STEP 4: Time to test it out! Make sure Design Mode is deselected.

How to Swap Values Using Macros in Excel

 

STEP 5: Click on the button now and you will see the values get swapped!

How to Swap Values Using Macros in Excel

 

Swap Values Using Macros in Excel

 

 

101 Macros Book

If you like this Excel tip, please share itEmail this to someone

email

Pin on Pinterest

Pinterest

Share on Facebook

Facebook

Tweet about this on Twitter

Twitter

Share on LinkedIn

Linkedin

See also  Unhide All Worksheets Using Macros In Excel
How to Swap Values Using Macros in Excel | MyExcelOnline
Bryan

Bryan is a best-selling book author of the 101 Excel Series paperback books.

Get Video Training

Advance your Microsoft Excel & Office Skills with the MyExcelOnline Academy!

Dramatically Reduce Repetition, Stress, and Overtime!
Exponentially Increase Your Chances of a Promotion, Pay Raise or New Job!

Learn in as little as 5 minutes a day or on your schedule.

Learn More!