XLA routines: EE_RearrangeColumns

Nick's picture
Use EE_RearrangeColumns to rearrange the cols for a data table
Sub EE_RearrangeColumns(SourceSheet As Worksheet, ParamArray TargetHeadings() As Variant)
    Dim intHeadings     As Integer
    Dim intCol          As Integer
    Dim rngTable        As range
    Dim rngColCopy      As range
    Dim rngPaste        As range
 
'http://excelexperts.com/xla-routines-eeRearrangeColumns    for updates on this sub routine

    Set rngTable = EE_Table(CStr(TargetHeadings(LBound(TargetHeadings))), SourceSheet)
 
    For intHeadings = LBound(TargetHeadings) To UBound(TargetHeadings)
        Set rngTable = EE_Table(CStr(TargetHeadings(LBound(TargetHeadings))), SourceSheet)
        intCol = 0
        On Error Resume Next
            intCol = Application.WorksheetFunction.Match(TargetHeadings(intHeadings), rngTable.Rows(1), 0)
        Err.Clear: On Error GoTo 0: On Error GoTo -1
        If intCol > 0 Then
            Set rngColCopy = rngTable.Columns(intCol)
            Set rngPaste = rngTable.Columns(intHeadings + 1).Cells(1, 1).Resize(rngColCopy.Rows.Count)
            If rngPaste.Address <> rngColCopy.Address Then
                rngColCopy.Cut
                rngPaste.Select
                rngPaste.Insert Shift:=xlToRight
                Application.CutCopyMode = False
            End If
        End If
    Next intHeadings
 
    Set rngTable = Nothing
    Set rngColCopy = Nothing
    Set rngPaste = Nothing
End Sub