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.
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 to use a macro to select a specific cell in a different workbook? It's not as straightforward of a proposition as ...Discover More
When you delete all the macros in a workbook, Excel may still think you have some there. Here's why that happens and what ...Discover More
Macros give you a great deal of control over creating, finding, renaming, and deleting files. This tip focuses on this ...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.