在ThisWorkbook新建VBA宏- Sub SortAndFilter()
- ' Order by Column A Asc,B Desc,and select B Max value rows into Sheet2.
- On Error Resume Next
- Dim rng As Range, oSort As Sort, sht1 As Worksheet, sht2 As Worksheet, i As Long, ii As Long
- Dim col1, col2, aValue
- col1 = 1 ' 第一列,有重复值
- col2 = 2 ' 第二列,取最大值
- Application.ScreenUpdating = False
- With ThisWorkbook
- Set sht1 = .Worksheets(1)
- Set sht2 = .Worksheets.Add(After:=.Worksheets(.Worksheets.Count))
- Set rng = sht1.UsedRange
- Set oSort = sht1.Sort
- With oSort
- .SortFields.Clear
- .SortFields.Add rng.Columns(col1), xlSortOnValues, xlAscending
- .SortFields.Add rng.Columns(col2), xlSortOnValues, xlDescending
- .SetRange rng
- .Header = xlYes
- .MatchCase = False
- .SortMethod = xlPinYin
- .Apply
- End With
- rng.Rows(1).Copy sht2.Rows(1)
- ii = 2
- aValue = Null
- For i = 2 To rng.Rows.Count
- If IsNull(aValue) Or aValue <> rng.Cells(i, col1).Value Then
- 'copy this row
- rng.Rows(i).Copy sht2.Cells(ii, 1)
- ii = ii + 1
- aValue = rng.Cells(i, col1).Value
- End If
- Next
- End With
- Application.ScreenUpdating = True
- End Sub
复制代码
|