Abhid
Abhid

Reputation: 274

Swap two excel columns in VB script

I have to copy data from one excel file to another. But the thing is that I have to swap two column data before I paste it in the destination.

I am very new to VB script and would love to hear from you guys regarding how to proceed.

Thanks!

Upvotes: 0

Views: 17926

Answers (1)

Richard
Richard

Reputation: 105

This is one way to do it. But you could have found this by recording a macro.

Sub Swap_Columns()
'Replace A:A with one your swapping
'C:C needs to be a blank column you can use to move the data
'Replace B:B with your other Column
'Replace Sheet1 with your sheet name
    Sheets("Sheet1").Columns("A:A").Cut Destination:=Columns("C:C")
    Sheets("Sheet1").Columns("B:B").Cut Destination:=Columns("A:A")
    Sheets("Sheet1").Columns("C:C").Cut Destination:=Columns("B:B")
End Sub  

If you want to use it on separate sheets put this in a module then you can call the Swap macro from anywhere on you workbook.

Sub Swap()
Dim ws As String
ws = Application.ActiveSheet.Name
    Sheets(ws).Columns("A:A").Cut Destination:=Columns("C:C")
    Sheets(ws).Columns("B:B").Cut Destination:=Columns("A:A")
    Sheets(ws).Columns("C:C").Cut Destination:=Columns("B:B")
End Sub

Upvotes: 2

Related Questions