根据另一个“排序”VBA一张纸(excel 2011)

时间:2015-10-13 14:05:13

标签: excel vba sorting multiple-columns excel-vba-mac

我想根据另一张纸(“sheet2”)对一张纸(“sheet1”)进行排序,因此相应地将单元格移动到另一张纸张中的单元格移动。

示例:

Sheet1: A45 contains number: 3
sheet2: A45 contains number: 200

排序(全部)sheet2(按列升序)(它代表超过一百列)

sheet2 A45 (200) moves to A98

我希望它能够移动:

sheet1 A45 (3) to A98

今天我正在尝试这个,我知道它有效,但只有PC excel 2003(法语),我不知道为什么它不适用于mac excel 2011(英文):

Sub Test()
 
    Dim PlageFe1 As Range
    Dim PlageFe2 As Range
    Dim Tbl()
    Dim I As Long
 
    'plage en colonne A de la Feuille "Feuil1"
    With Worksheets("Feuil1")
 
        Set PlageFe1 = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
 
    End With
 
    'plage en colonne A de la Feuille "Feuil2"
    With Worksheets("Feuil2")
 
        Set PlageFe2 = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
 
    End With
 
    'dimensionne le tableau par rapport à une des deux plages (ici la 1)
    ReDim Tbl(1 To 2, 1 To PlageFe1.Count)
 
    'fusionne les deux plages dans le tableau
    For I = 1 To UBound(Tbl, 2)
 
        Tbl(1, I) = PlageFe1(I)
        Tbl(2, I) = PlageFe2(I)
 
    Next I
 
    'effectue le tri (adapter le signe < ou > dans la porc "Tri")
    Tri Tbl()
 
    'puis réaffecte les valeurs
    For I = 1 To UBound(Tbl, 2)
 
        PlageFe1(I) = Tbl(1, I)
        PlageFe2(I) = Tbl(2, I)
 
    Next I
 
End Sub
 
Sub Tri(Tbl())
 
    Dim Tempo1, Tempo2
 
    Dim I As Long, J As Long
            'éffectue un tri décroissant "<"
            'pour un tri croissant ">"
    For I = 1 To UBound(Tbl, 2) - 1
 
        For J = I + 1 To UBound(Tbl, 2)
 
            'tri sur l'index 1
            If Tbl(1, I) > Tbl(1, J) Then
 
                Tempo1 = Tbl(1, J)
                Tempo2 = Tbl(2, J)
                Tbl(1, J) = Tbl(1, I)
                Tbl(2, J) = Tbl(2, I)
                Tbl(1, I) = Tempo1
                Tbl(2, I) = Tempo2
 
            End If
 
    Next J, I
 
End Sub

1 个答案:

答案 0 :(得分:0)

也许你可以试试这个:

Sub SpecialSort()

Dim Rng1 As Range, Rng2 As Range, Rng3 As Range

' Current Selection
Set Rng1 = Selection
' Equivalent Selection on sheet 1
Set Rng2 = Sheets(1).Range(Rng1.Address)

' Cut the part from the first sheet
Rng2.Cut
' Insert it before the range to be sorted
Rng1.Insert Shift:=xlToRight
' Keep track of this new inserted part
Set Rng3 = Rng1.Parent.Range(Rng2.Address)
' Sort by the column in question
With Rng1.Parent.Sort
    .SortFields.Clear
    .SortFields.Add Key:=Rng1, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    .SetRange Union(Rng1, Rng3): .Header = xlNo: .MatchCase = False: .Orientation = xlTopToBottom: .SortMethod = xlPinYin: .Apply
End With
' Cut the sorted part
Rng3.Cut
' Put it back
Rng2.Parent.Select: Rng2.Select
ActiveSheet.Paste
' Delete the section you cut
Rng3.Delete Shift:=xlToLeft

Set Rng1 = Nothing: Set Rng2 = Nothing: Set Rng3 = Nothing

End Sub

通过选择范围(包括整列),它在第一张纸上找到等效范围,并根据选择的排序方式(使用第一列作为关键字)对第二个范围进行排序。 / p>

即使这不是您所需要的,也许您可​​以相应地修改它。