Search code examples
excelvba

Delete an array column, and change position of two columns


So let's say i have and 4x4 array of various numbers.

I want to delete the third array column, and switch positions of the second and fourth columns within the array.

The ultimate goal is copying information from a sheet into an array, and prepping the array to paste into another sheet.

How would I be able to do this?

Sub test()
Dim Arr as variant
Arr=Sheets("Worksheet").Range("A1:D4")
'Delete third column
'Switch second and what was the fourth but now is the 3rd column.
Sheets("Sheet2").Range("A1").Resize(UBound(Arr, 1), UBound(Arr, 4)) = Arr
End Sub

Solution

  • Delete 'n' Switch Column in Array

    The code overwrites the third column with data from the second column, and at the same time overwrites the second column with data from the fourth column. Finally the last (fourth) column is removed.

    Sub deleteAndSwitch()
        
        Dim wb As Workbook: Set wb = ThisWorkbook
    
        Dim Data As Variant, i As Long
        Data = wb.Worksheets("Worksheet").Range("A1:D4").Value
        For i = 1 To UBound(Data)
            Data(i, 3) = Data(i, 2)
            Data(i, 2) = Data(i, 4)
        Next i
        ReDim Preserve Data(1 To UBound(Data), 1 To 3)
        'e.g.
        wb.Worksheets("Sheet2").Range("A1") _
          .Resize(UBound(Data), UBound(Data, 2)).Value = Data
     
    End Sub