VBA Plus / Macros Chapter – 1 (Swap Values – 1)

VBA Plus / Macros Chapter – 1 (Swap Values – 1) featured illustration
⏱ 2 min readUpdated 4 November 2026

This example teaches you how to swap two values in Excel VBA. You will often need this structure in more complicated programs as we will see later.

Situation:

Advertisement

Two values on your worksheet.

Swap Values in Excel VBA

Place a command button on your worksheet and add the following code lines:

1. First, we declare a variable called temp of type Double.Dim temp As Double

2. We initialize the variable temp with the value of cell A1.temp = Range(“A1”).Value

3. Now we can safely write the value of cell B1 to cell A1 (we have stored the value of cell A1 to temp so we will not lose it).Range(“A1”).Value = Range(“B1”).Value

4. Finally, we write the value of cell A1 (written to temp) to cell B1.Range(“B1”).Value = temp

5. Click the command button two times.

Result:

Swap Values Result
Swap Values Result
⚑ Interactive Practice Lab & Formula Tester:

Test formulas dynamically in our web formula laboratory or download the companion Excel workbook.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free Β· AI can be wrong

Leave a Reply

Your email address will not be published. Required fields are marked *