Delete an array column, and change position of two columns

前端 未结 3 1701
醉话见心
醉话见心 2021-01-16 02:23

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

相关标签:
3条回答
  • 2021-01-16 03:03

    Alternative via Application.Index() function

    For the sake of the art an approach without loops allowing to get any new column order defined just by listing the new column positions via

         Array(1, 4, 2)
    

    in other words

    • the 1st column,
    • (the 3rd one omitted=deleted),
    • the remaining columns 4 and 2 in switched order*.

    Btw it would even be possible to repeat columns, just insert its number at any position in the column array, e.g. to repeat a date column with changed formatting (assuming date in column 4 e.g. via Array(1, 4, 4, 2)

    Sub DeleteAndSwitch()
    '[1]get data
        Dim data: data = Sheet1.Range("A1:D4")
    '[2]reorder columns via Array(1, 4, 2), i.e. get 1st column, 4th and 2nd column omitting the 3rd one
    '   (evaluation gets all existing rows as vertical 2-dim array)
        data = Application.Index(data, Evaluate("row(1:" & UBound(data) & ")"), Array(1, 4, 2))
    '[3]write to any target
        Sheet2.Range("A1").Resize(UBound(data), UBound(data, 2)) = data
    End Sub
    
    

    Related link

    See Some peculiarities of the the Application.Index() function

    0 讨论(0)
  • 2021-01-16 03:16

    The best way to deal with this issue is to use a better structure than an array. E.g a dictionary of arrays (Collection, Scripting.Dictionary, Arraylist, jagged array). So instead of reading a two dimensional section of a spreadsheet into an array, iterate over the columns and add each column as an array to a dictionary. You can then set up a second simpler dictionary to map each current index to its new index. No need to delete anything as you will only copy back, column array by column array, those columns you actually need.

    0 讨论(0)
  • 2021-01-16 03:23

    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
    
    0 讨论(0)
提交回复
热议问题