Please Note: This article is written for users of the following Microsoft Excel versions: 97, 2000, 2002, and 2003. If you are using a later version (Excel 2007 or later), this tip may not work for you. For a version of this tip written specifically for later versions of Excel, click here: Swapping Two Numbers.
by Allen Wyatt
(last updated December 13, 2018)
If you do any serious macro programming, there will eventually come a time when you want to swap the values in two numeric variables. In some versions of BASIC, there are commands that handle this. VBA leave you to our own devices, however. The following technique should do the trick for most people:
TempNum = MyNum1 MyNum1 = MyNum2 MyNum2 = TempNum
When completed, the values in MyNum1 and MyNum2 have been swapped, and TempNum doesn't matter since it was intended (by this technique) as a temporary variable anyway.
ExcelTips is your source for cost-effective Microsoft Excel training. This tip (2525) applies to Microsoft Excel 97, 2000, 2002, and 2003. You can find a version of this tip for the ribbon interface of Excel (Excel 2007 and later) here: Swapping Two Numbers.
Professional Development Guidance! Four world-class developers offer start-to-finish guidance for building powerful, robust, and secure applications with Excel. The authors show how to consistently make the right design decisions and make the most of Excel's powerful features. Check out Professional Excel Development today!
If your macro closes workbooks, you'll want to make sure that it will save any changes you made to the workbook. Here's ...Discover More
Add a graphic to a worksheet as part of an Image object, and you can use some very handy event handlers to figure out the ...Discover More
A great way to customize Excel is to add your macros to a toolbar. That way you can run them quickly and easily.Discover More
FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."
Got a version of Excel that uses the menu interface (Excel 97, Excel 2000, Excel 2002, or Excel 2003)? This site is for you! If you use a later version of Excel, visit our ExcelTips site focusing on the ribbon interface.