根据第2行的值重新组织列

我正在尝试根据第2行中单元格的值按字母顺序对列进行sorting。

无法弄清楚这里有什么问题 – 它似乎只适用于第一列,然后停止。

Sub reorganise() Dim v As Variant, x As Variant, findfield As Variant Dim oCell As Range Dim iNum As Long Dim wsa As Worksheet Set wsa = Worksheets("Skills") v = Array(wsa.Range("B2", wsa.Cells(2, wsa.Columns.Count).End(xlToLeft))) For x = LBound(v) To UBound(v) findfield = v(x) iNum = iNum + 1 Set oCell = wsa.Rows(2).Find(What:=findfield, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False) If Not oCell.Column = iNum Then Columns(oCell.Column).Cut Columns(iNum).Insert Shift:=xlToRight End If Next x End Sub 

好吧,我已经知道了..有点复杂,但这里是完整的代码:

 Sub reorganise() Dim v Dim x Dim findfield As Variant Dim oCell As Range Dim iNum As Long Dim wsa As Worksheet Dim inputArray() As Variant Set wsa = Worksheets("Skills") With wsa Set v = .Range("A2", .Cells(2, .Columns.Count).End(xlToLeft)) End With v = Application.Transpose(v) Call BubbleSort(v) For x = LBound(v, 1) To UBound(v, 1) findfield = v(x, 1) iNum = iNum + 1 Set oCell = wsa.Rows(2).Find(What:=findfield, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False) If Not oCell.Column = iNum Then Columns(oCell.Column).Cut Columns(iNum).Insert Shift:=xlToRight End If Next x End Sub Sub BubbleSort(arr) Dim strTemp As String Dim i As Long Dim j As Long Dim lngMin As Long Dim lngMax As Long lngMin = LBound(arr, 1) lngMax = UBound(arr, 1) For i = lngMin To lngMax - 1 For j = i + 1 To lngMax If arr(i, 1) > arr(j, 1) Then strTemp = arr(i, 1) arr(i, 1) = arr(j, 1) arr(j, 1) = strTemp End If Next j Next i End Sub 

除了你所说的基本上,我不得不:

  • 转置数组
  • 更改LBoundUboundfindfield语法
  • 想出一个额外的程序来按字母顺序排列数组的值

1)将范围直接分配给variablesvariablesv – 不带数组function。 当使用数组函数时,你正在做的是将一个元素的数组(包括你的范围作为一个数组返回)传递给variablesv

2)v将包含一个2维数组:

  • 第一维将是1 – 返回一行
  • 第二个维度将与该范围返回的列数一样多

然后遍历这个数组的第二个维度 – 我没有检查代码的其余部分,但这应该让你的方式