如何通过列标题名称重新排列列。 我需要每周处理一份报告,原始工作表有23列。我抽象了其中的一部分作为示例。
原始列顺序: QTY 付款条件 契约(Contract)号等
所需列顺序:契约(Contract)号、付款条件、数量等
知道如何使用 VBA 代码自动重新排列列吗? 非常感谢。
最佳答案
这对你来说有什么作用?我尝试只使用四列,它对我有用。
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
注意:没有真正的错误处理,因此如果您的 header 需要进行 TRIM()
编辑或检查错误信息,您需要添加一些内容来执行此操作。
关于excel - 如何通过列标题名称重新排列 Excel 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46529391/