Sorting Alphabetically and by Cell Color

╄→尐↘猪︶ㄣ 提交于 2019-12-18 07:09:05

问题


I'm trying to sort multiple lists Alphabetically and by Cell Color but within a certain range (so it doesn't take too long). Basically the VBA is suppose to select for example column B rows 3-88, sort by alphabet, then sort by color. Then move to next column C3:C88, etc, until column NY.

When I try it, I get Run-time error 1004: Mathod "Range" of object '_Global' failed.

This is my VBA:

Sub SortAlphaColor()
' Sorts rows within a list from A-Z
' Run Clean all first to avoid sorting blanks
' Set maximum range to avoid sorting too many rows

    Dim rngFirstRow As Range
    Dim rng As Range
    Dim ws As Worksheet

    Application.ScreenUpdating = False
    Set ws = ActiveSheet
    Set rngFirstRow = ws.Range("B3:NY3")
    For Each rng In rngFirstRow
        With ws.Sort
            .SortFields.Clear
            .SortFields.Add Key:=rng, Order:=xlAscending
            'assuming there are no blank cells..
            .SetRange ws.Range(rng, rng.Range("B88").End(xlUp))
                'VBA from second module
                .SortFields.Add(Range(rng), xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue.Color = RGB(198, 239, 206) <- this line is highlighted in debug
                .Orientation = xlTopToBottom
                .SortMethod = xlPinYin
            .Header = xlYes
            .MatchCase = False
            .Apply
        End With
    Next rng
    Application.ScreenUpdating = True
End Sub

回答1:


This worked for me:

Sub SortAlphaColor()

    Dim rngFirstRow As Range
    Dim rng As Range, rngSort As Range
    Dim ws As Worksheet

    Application.ScreenUpdating = False
    Set ws = ActiveSheet
    Set rngFirstRow = ws.Range("B3:NY3")
    For Each rng In rngFirstRow.Cells
        With ws.Sort

            Set rngSort = rng.Resize(86, 1) 'to row 88

            .SortFields.Clear
            .SortFields.Add Key:=rng, SortOn:=xlSortOnValues, _
                            Order:=xlAscending, DataOption:=xlSortNormal
            .SortFields.Add(rng, xlSortOnCellColor, xlAscending, , xlSortNormal). _
                            SortOnValue.Color = RGB(198, 239, 206)
            .SetRange rngSort
            .Header = xlNo
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply

        End With
    Next rng
    Application.ScreenUpdating = True
End Sub


来源:https://stackoverflow.com/questions/17530785/sorting-alphabetically-and-by-cell-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!