Moving Columns based on header name

前端 未结 2 1697
一整个雨季
一整个雨季 2020-12-20 03:19

I have a macro that rearranges the columns into a particular order.

Sub ArrangeColumns()

\' ArrangeColumns Macro

    Columns(\"C:C\").Select
    Applicatio         


        
2条回答
  •  情书的邮戳
    2020-12-20 04:15

    If you know all the header names, you can define an array of the header names and use the array's index to move the columns around.

    Sub columnOrder()
    Dim search As Range
    Dim cnt As Integer
    Dim colOrdr As Variant
    Dim indx As Integer
    
    colOrdr = Array("id", "last_name", "first_name", "gender", "email", "ip_address") 'define column order with header names here
    
    cnt = 1
    
    
    For indx = LBound(colOrdr) To UBound(colOrdr)
        Set search = Rows("1:1").Find(colOrdr(indx), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)
        If Not search Is Nothing Then
            If search.Column <> cnt Then
                search.EntireColumn.Cut
                Columns(cnt).Insert Shift:=xlToRight
                Application.CutCopyMode = False
            End If
        cnt = cnt + 1
        End If
    Next indx
    End Sub
    

    Any column not named in the array will appear on the right of the ones named.

提交回复
热议问题