Search code examples
excelvbacell

Swap any two cells using excel VBA - including non-adjacent cells


I need to swap two cell values. Holding Shift Key then pick & drop method don't work here. so I decided to create a macro in which I can get Active cell address by

ActiveCell.Address

but how can I get address of the cell which I had copied before running this macro? to elaborate more these are the steps to swap values.

Copy a cell

Select another cell in the same sheet

Run Macro to swap values (which will save activecell value as string and paste the copied cell value)

Updated: For Switching Columns, Cells or Rows using VBA in less than Three steps please follow this https://youtu.be/MaiSBVguh28


Solution

  • This sub will do the trick:

    Sub swapper()
    Dim cellfirst As String, cellsecond As String
    If Not Selection.Cells.Count = 2 Then
        MsgBox ("Please only select two cells")
            Else
            If Selection.Areas.Count > 1 Then
                cellfirst = Selection(1).Value
                cellsecond = Selection.Areas(2).Value
                Selection(1).Value = cellsecond
                Selection.Areas(2).Value = cellfirst
                    Else
                    cellfirst = Selection(1).Value
                    cellsecond = Selection(2).Value
                    Selection(1).Value = cellsecond
                    Selection(2).Value = cellfirst
            End If
    End If
    End Sub
    

    It will test if two cells are selected, if not give an error message. Then it will test if the cells are apart or close together. Then based on that store the values of both cells in strings, swap the strings, and print back to cell.

    Note: Select two different cells by holding ctrl and clicking on both cells.

    I realise this isn't 1 for 1 what you've asked for, but why go through the effort of copying something yourself when you can have the macro do it all for you?