excel vba按颜色排序,然后按值排序

时间:2016-05-19 19:29:21

标签: excel vba excel-vba

我一直在尝试根据自己的情况调整另一个答案,我无法让它发挥作用。我试图按一个单元格的颜色(它们是无颜色或一种特定颜色)进行排序,然后按第二个单元格中的值进行排序。这是我的代码:

Application.ScreenUpdating = False
xL.Sheets(sheet).Sort.SortFields.Clear
xL.Sheets(sheet).Sort.SortFields.Add(Range("B1:B" + CStr(rowCount)), _
        xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue.Color = RGB(216, 228, 188)
xL.Sheets(sheet).Sort.SortFields.Add Range("H1:H" + CStr(rowCount)), _
        xlSortOnValues, xlDescending, , xlSortNormal
With xL.Sheets(sheet).Sort
    .SetRange ("A1:M" + Trim(Str(rowCount)))
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .Apply
End With
Application.ScreenUpdating = True

当我运行时,我收到以下错误:运行时错误'-2147417851(80010105)':对象'SortFields'的方法'添加'失败。它发生在第一个“.SortFields.Add”上。谁能看到我做错了什么?谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用基本脚本进行排序:

对于Office 2013:

Application.ScreenUpdating = False
ActiveWorkbook.Worksheets(sheet).Sort.SortFields.Clear
ActiveWorkbook.Worksheets(sheet).Sort.SortFields.Add(Range("B2:B" & rowCount), _
    xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue.Color = RGB(216, 228, 188)
With ActiveWorkbook.Worksheets(sheet).Sort
    .SetRange Range("A1:M" & rowCount)
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

ActiveWorkbook.Worksheets(sheet).Sort.SortFields.Clear
ActiveWorkbook.Worksheets(sheet).Sort.SortFields.Add Key:=Range("B2:B" & rowCount), _
    SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets(sheet).Sort
    .SetRange Range("A1:M" & rowCount)
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With
Application.ScreenUpdating = True