根据第2行值重新组织列

时间:2014-08-09 15:46:27

标签: excel excel-vba vba

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

无法弄清楚这里出了什么问题 - 它似乎仅适用于第一列然后停止。

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

2 个答案:

答案 0 :(得分:1)

好的,我已经弄清楚..有点复杂但是这里是完整的代码:

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

基本上除了你所说的,我还是要:

  • 转置数组
  • 更改LBoundUbound以及findfield语法
  • 提出一个额外的程序来按字母顺序排列数组的值

答案 1 :(得分:0)

1)直接将范围分配给变量变量v - 没有Array函数。使用数组函数时,您正在做的是将一个元素的数组(包括作为数组返回的范围)分配给变量v

2)v将包含2维数组:

  • 第一个维度为1 - 返回一行
  • 第二个维度将是范围
  • 返回的列数

然后循环遍历这个数组的第二个维度 - 我没有检查其余的代码,但是这应该可以帮助你了解