excel - 如何通过列标题名称重新排列 Excel 列

标签 excel vba

如何通过列标题名称重新排列列。 我需要每周处理一份报告,原始工作表有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() 编辑或检查错误信息,您需要添加一些内容来执行此操作。

enter image description here

关于excel - 如何通过列标题名称重新排列 Excel 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46529391/

相关文章:

vba - 循环和偏移

excel - 选择文件夹路径 - 不读取所选文件夹中的文件

VBA创建对象

php - 如何使用 PHP 将 SQL 表导出为 excel 格式

php - HTML表格数据传输到MS Excel?

vba - 带有输入框的变量与模块中的多个子变量

vba - 在 Excel 中通过 VBA 编辑自定义样式

vba - 如何编辑在 VBA 中以阅读模式打开的 Word 文档

javascript - VBA JavaScript 对象不支持此属性或方法

vba - 根据单元格中的值对单元格进行颜色