在Excel 2007中使用多列进行排名

时间:2018-10-04 08:15:53

标签: excel-2007

在excel中自动对A列进行排序并为B列排名。

A B C(排名)

4 289 2

7 465 3

4 395 1

1 个答案:

答案 0 :(得分:0)

假设您希望数据看起来像这样(您希望对A和B列进行排序,然后在C列中对其进行排名):

+----------+----------+----------+
| Col    A | Col    B | Col    C |
+----------+----------+----------+
|        4 |      395 |          |
|        4 |      289 |          |
|        7 |      465 |          |
+----------+----------+----------+

您可以使用VBA代码来实现。 ALT + F11打开VBA编辑器。 然后通过右键单击将其粘贴到模块中 add module.

粘贴以下代码:

Sub SortColumns()
With Worksheets("Sheet1").Sort 'Name the worksheet
     .SortFields.Add Key:=Range("A1"), Order:=xlAscending 'Column A, sort it by Ascending values
     .SortFields.Add Key:=Range("B1"), Order:=xlDescending 'Column B, sort it by Descending values
     .SetRange Range("A1:C13") ' Which range you want to apply the filter for
     .Header = xlYes 'Does your data has header
     .Apply 'Apply autofilter
End With

'Add Rankings:
Dim lrow As Integer

lrow = Cells(Rows.Count, "B").End(xlUp).Row 'find last row in Column B
Cells(2, "C").Value = 1 'Set first rank value in Column C for row 2
For i = 3 To lrow 'Loop through column B to set each value
    Cells(i, "C").Value = Cells(i - 1, "C").Value + 1 'Start at row 3, set the value for current row (i) by taking the previous row and add + 1
Next i
End Sub

运行代码后的输出如下所示:

+----------+----------+----------+
| Col    A | Col    B | Col    C |
+----------+----------+----------+
|        4 |      395 |        1 |
|        4 |      289 |        2 |
|        7 |      465 |        3 |
+----------+----------+----------+