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.
Solve Real Business Problems Master business modeling and analysis techniques with Excel and transform data into bottom-line results. This hands-on, scenario-focused guide shows you how to use the latest Excel tools to integrate data from multiple tables. Check out Microsoft Excel 2013 Data Analysis and Business Modeling today!
When you record a macro, make sure that you know how Excel is recording your cell movements. This tip explains the ...Discover More
Excel is great for collecting all sorts of information. You might even use it to create a catalog of your photos. Working ...Discover More
Need to figure out an absolute value within your macro code? It's easy to do using the Abs function, described in this tip.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.