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 February 22, 2014)
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.
Create Custom Apps with VBA! Discover how to extend the capabilities of Office 2013 (Word, Excel, PowerPoint, Outlook, and Access) with VBA programming, using it for writing macros, automating Office applications, and creating custom applications. Check out Mastering VBA for Office 2013 today!
Need a quick way to change the default drive and directory in a macro you are writing? Here's the commands to do it and a ...Discover More
Excel allows you to fill a cell's background with just about any color you want. If you need to determine the RGB value of ...Discover More
Got too much information in a single cell? Here's how you can use a macro to pull apart that information and put it into ...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.