Swap selected cell values

  • Thread starter Thread starter Cortez
  • Start date Start date
C

Cortez

I am looking for a simple macro to swap the contents of two selected
cells. The cells might not be next to each other.

I know what I want it to do, but I don't know vba well enough.

If anyone has a moment to help, here is what I want to do.

Select cell1, could be A1
Control-Click additional selection of cell2, could be C1

Hot-Key Macro to:
Assign cell1 value to variable1
Assign cell2 value to variable2
Assign variable1 value to cell2
Assign variable2 value to cell1

Note: the specific cells being selected will not always be the same.

So after the macro is run the values that started in cells A1 and C1
would swap with each other.

Any suggestions would be appreciated.

TK
 
Sub swap_um()
Dim v0 As Variant
Dim v1 As Variant
Dim s(2) As String
If Selection.Count <> 2 Then Exit Sub
i = 0
For Each rr In Selection
s(i) = rr.Address
i = i + 1
Next
v0 = Range(s(0)).Value
v1 = Range(s(1)).Value
Range(s(1)).Value = v0
Range(s(0)).Value = v1
End Sub
 
Hi,

Try this

Sub Swap()
Y = Selection.Areas(1)
Selection.Areas(1) = Selection.Areas(2)
Selection.Areas(2) = Y
End Sub

If this helps, please click the Yes button

Cheers,
Shane Devenshire
 
Excellent, thank you very much!

TK

Sub swap_um()
Dim v0 As Variant
Dim v1 As Variant
Dim s(2) As String
If Selection.Count <> 2 Then Exit Sub
i = 0
For Each rr In Selection
    s(i) = rr.Address
    i = i + 1
Next
v0 = Range(s(0)).Value
v1 = Range(s(1)).Value
Range(s(1)).Value = v0
Range(s(0)).Value = v1
End Sub
--
Gary''s Student - gsnu2007k













- Show quoted text -
 
That also works for my stated need. It errors out if the selection
was created as a range of two cells, but otherwise is very simple.
Thank you.
 
Hi,

Glad to help. If you are interested in multiple cells in each range, will
they always be in a column, a row, or any rectangle?

Cheers,
Shane Devenshire
 
Back
Top