【发布时间】:2020-05-26 04:46:28
【问题描述】:
对不起,我找不到这个代码
代码根据工作表中所有列的列表对列重新排序
它适用于大量列,但它要求您列出工作表中的所有列,否则会删除未列出的列
有复制粘贴的版本,但速度很慢,不适合大量列
我只想列出我想要重新排序到工作表开头的列,所有其他列都按照它们所在的顺序排列 在重新排序的列之后
没有运气这样做
谢谢
Sub colOrder()
' Purpose: restructure range columns
With Sheet1 ' worksheet referenced e.g. via CodeName
' [0] identify range
Dim rng As Range, lastRow&, lastCol&
lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row ' get last row and last column
lastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
Set rng = .Range(.Cells(1, 1), .Cells(lastRow, lastCol))
' ~~~~~~~~~~~~
' [1] get data
' ~~~~~~~~~~~~
Dim v: v = rng ' assign to 1-based 2-dim datafield array
' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
' [2] restructure column order in array in a one liner
' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
v = Application.Index(v, Evaluate("row(1:" & lastRow & ")"), getColNums(v))
' [3] write data back to sheet
rng = vbNullString ' clear orginal data
.Range("A1").Resize(UBound(v), UBound(v, 2)) = v ' write new data
End With
End Sub
上述主程序调用的辅助函数
辅助函数只返回一个数组,其中包含在当前标题中找到的正确列号;它使用Application.Match 来查找货币:
Function getColNums(arr) As Variant()
' Purpose: return array of found column number order, e.g. Array(3,2,1,4,6,5)
Dim colOrdr(), titles ' wanted order, current titles
colOrdr = Array("id", "last_name", "first_name", "gender", "email", "ip_address") 'define column order with header names here
titles = Application.Transpose(Application.Transpose(Application.Index(arr, 1, 0)))
Dim i&, ii&, pos ' array counters, element position
ReDim tmp(0 To UBound(colOrdr)) ' temporary array to collect found
positions
For i = 0 To UBound(colOrdr) ' loop through titles in wanted order
pos = Application.Match(colOrdr(i), titles, 0) ' check positions
If Not IsError(pos) Then tmp(ii) = pos: ii = ii + 1 ' remember found positions, increment
counter
Next I
ReDim Preserve tmp(0 To ii - 1) ' remove empty elements
getColNums = tmp ' return array with current column
numbers (1-based)
End Function
【问题讨论】:
-
Power Query / Get & Transform 做得很好。
-
您可以将
Range.Find用于您的数组循环,找到时只需使用Cut/Paste。如果不在您的数组中,这将确保没有任何内容被删除 -
如果我使用复制粘贴它会变慢很多列
-
抱歉,我找不到此代码的来源:请参阅 Moving columns based on header name 于 2019 年 6 月 26 日回答