根据另一个列的值顺序对列进行排序

时间:2014-03-12 06:00:47

标签: vba excel-vba excel

我在spreadsheet1中有两列:

Col1  Col2     

1     PDC      
2     SR3      
3     PDC      
4     VBM      
5     VBM
6     GAL
7     VBM
8     GAL
9     PDC

我在电子表格2中有一列:

Col1

PDC
SR3
VBM
GAL

如何根据spreadsheet2 Col1中的顺序对电子表格1中的Col1和Col2进行排序?

2 个答案:

答案 0 :(得分:0)

试试这段代码:

Sub test()
    Dim wb As Workbook
    Dim ws1 As Worksheet
    Dim ws2 As Worksheet
    Dim lastrow As Long
    Dim rng As Range

    'if workbook2 is already opened
    Set wb = Workbooks("Book2") ' change Book2 to suit
    'if workbook2 is not opened
    'Set wb = Workbooks.Open("C:\Book2.xlsx")

    'change sheet1 to suit
    Set ws1 = ThisWorkbook.Worksheets("Sheet1")
    'change sheet2 to suit
    Set ws2 = wb.Worksheets("Sheet2")

    With ws1
        'change column B to column with your values "PDC", "SR3" and so on
        lastrow = .Cells(.Rows.Count, "B").End(xlUp).Row
        'change to address of range you wnat to sort
        Set rng = .Range("A1:B" & lastrow)
        With rng.Offset(, rng.Columns.Count).Resize(, 1)
            .EntireColumn.Insert
            .Offset(, -1).FormulaR1C1 = "=MATCH(RC[-1],'[" & wb.Name & "]" & ws2.Name & "'!C1:C1,0)"
            .Offset(, -1).Value = .Offset(, -1).Value
        End With
        With rng.Resize(, rng.Columns.Count + 1)
            .Sort Key1:=.Cells(1, .Columns.Count), Order1:=xlAscending, Header:=xlGuess
            .Cells(1, .Columns.Count).EntireColumn.Delete
        End With
    End With

    wb.Close
End Sub

<强> Explanaiton:

  1. 有两本工作簿。代码应该放在第一个工作簿中(您要对范围进行排序)
  2. 主要思想是添加带有=MATCH(B1,[Book2]Sheet2!A:A,0)等公式的临时列,以获取A列(工作簿2)中B列(工作簿1)的值行数。
  3. 根据此数字排序范围。
  4. 删除临时列
  5. enter image description here

    备注:

    下一行假设该列带有&#34; PDC&#34;,&#34; SR3&#34; (在工作簿1中)是选定范围(Set rng = .Range("A1:B" & lastrow))中的最后一个:

    .Offset(, -1).FormulaR1C1 = "=MATCH(RC[-1],'[" & wb.Name & "]" & ws2.Name & "'!C1:C1,0)"
    

    如果不成立,请将RC[-1]更改为RC[-2],如果此列为最后一列,则为{/ p>}。

    C1:C1公式的一部分意味着在workbook2列中使用&#34; PDC&#34;,&#34; SR3&#34;是列A(列№1)。如果不成立,请将其更改为C5:C5,这意味着该列为E(第5列)。

答案 1 :(得分:0)

我发现这段代码看起来更简单,效果很好。

Sub NewSortTest()
    Dim keyRange As Variant
    Dim sortNum As Long

    keyRange = ActiveWorkbook.Worksheets("Sheet2").Cells.Range("A1:A10").Value

    Application.AddCustomList ListArray:=keyRange
    sortNum = Application.CustomListCount

    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add key:=Range("A1:A20"), SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:=sortNum, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sheet1").Sort
        .SetRange Range("A1:B20")
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub