Excel VBA: Swap Cell Values with the Adjacent Column
Question details
The user needs an Excel VBA macro to swap selected cell values with values in the adjacent column.

- Product
- Microsoft Excel VBA
- Device & OS
- not provided
- Scenario
- Exchange each nonempty selected cell's value with the value in the cell immediately to its right.
- Observed behavior
- The existing procedure uses an invalid HasValue property and overwrites a value before the swap is complete.
Select cells in a single column, with an editable column to their right. Avoid merged cells, protected cells, and formulas you need to preserve: assigning values replaces formulas.
Use a temporary variable to swap values in Excel VBA
Use this macro to exchange each nonempty selected value with the cell immediately to its right.
Excel VBA Range objects do not have a HasValue property. The macro checks the cell's Value instead and stores it in a Variant before making either assignment.
In desktop Excel, open the Developer tab and select Visual Basic. If the Developer tab is hidden, enable it in Excel's ribbon settings.
In the VBA editor, select Insert > Module and paste this code: Sub SwapTextWithRightColumn() Dim cell As Range, oldValue As Variant For Each cell In Selection If Not IsError(cell.Value) Then If cell.Value <> "" Then oldValue = cell.Value cell.Value = cell.Offset(0, 1).Value cell.Offset(0, 1).Value = oldValue End If End If Next cell End Sub
Return to the worksheet and select the cells to swap in one column. Select Developer > Macros, choose SwapTextWithRightColumn, and click Run.
To keep the VBA code in the workbook, select File > Save As and choose Excel Macro-Enabled Workbook (.xlsm).

Work with Excel spreadsheets in WPS Office
WPS Office is a free, lightweight alternative with a familiar spreadsheet interface. Open compatible Excel files and continue working with your data in WPS Spreadsheets; VBA support can vary by version and environment.

Frequently Asked Questions
Why does HasValue cause an error in Excel VBA?
HasValue is not an Excel VBA Range property. Use cell.Value to check the cell's value, as shown in the macro.
What happens if the cell to the right is blank?
The selected cell becomes blank, and its original value moves into the cell to the right. A selected cell that is already empty is skipped.
Can I select several adjacent columns before running the macro?
Select cells in one column instead. With multiple adjacent columns selected, a cell can be changed by an earlier swap and then swapped again.
Will the macro swap formulas and formatting?
No. It assigns cell values, so formulas in either cell are replaced by their results. Cell formatting remains in place.
How do I keep the macro for later use?
In Excel, select File > Save As and save the workbook as an Excel Macro-Enabled Workbook (.xlsm).




