如何按列标题名称重新排列列。 我需要每周处理一份报告,原始工作表有23列。我将其中一部分抽象为例。
原始列序列:QTY Payment Terms Contract No. etc
所需的列序列:Contract No. Payment terms QTY etc
知道如何使用VBA代码自动化列重新排列吗? 非常感谢提前。
答案 0 :(得分:0)
这对你有什么用?我尝试了只有四列,它对我有用。
Sub rearrange_Columns()
Dim correctOrder() As Variant
Dim lastCol As Long
Dim headerRng As Range, cel As Range
Dim mainWS As Worksheet
Set mainWS = ActiveWorkbook.Worksheets("Sheet1")
' Edit this to be the correct order you need
correctOrder() = Array("Column A", "Column B", "Column C", "Column D")
' Now, we know that the number of headers you have to rearrange are `UBound(CorrectOrder)+1`
With mainWS
lastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
Set headerRng = .Range(.Cells(1, 1), .Cells(1, lastCol))
End With
Dim newWS As Worksheet
Set newWS = ActiveWorkbook.Sheets.Add
newWS.Name = "Rearranged Sheet"
Dim col As Long
With newWS
For col = 1 To lastCol
For Each cel In headerRng
If cel.Value = correctOrder(col - 1) Then
mainWS.Columns(cel.Column).Copy .Columns(col)
Exit For
End If
Next cel
Next col
End With
End Sub
注意:没有真正的错误处理,因此如果您的标题需要TRIM()
或检查错误信息,您需要添加一些内容。