Avatar of vbaabv
vbaabv
Flag for United States of America asked on

Excel VBA sort 14 contiguous columns by colors

I am doing the same sort repeatedly in the same worksheet, only the rows are changing. I am basically sorting the worksheet section by section (each section being a group of contiguous rows).

The repeated sort is actually 4 similar sorts. All four are sorts of columns D thru R and are sorts by cell color.
1. Sort columns D thru R by cell color (light red, 255, 199, 206) putting light red at the top. 2. Sort columns D-R by cell color (dark red, 192, 0, 0)  puts dark red at top.
3. Sort same columns and put light green (198, 239, 206) on bottom.
4. Sort again (same columns, D-R) and put dark green (79, 98, 40) on bottom.

Caveat: some of the columns, D-R, will not have the given color. I need to check to see if the given color is present in column and if it is not then change to one of the other colors or no color.

 With each sort the rows change, but the rows are always contiguous.

This is what I now have:

Sub ColorSort()
'
' ColorSort Macro
'
    Range("A2341:Y2368").Select
    ActiveWorkbook.Worksheets("Sheet24 (4)").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet24 (4)").Sort.SortFields.Add Key:=Range( _
        "D2341:D2368"), SortOn:=xlSortOnCellColor, Order:=xlAscending, DataOption _
        :=xlSortNormal
    ActiveWorkbook.Worksheets("Sheet24 (4)").Sort.SortFields.Add(Range( _
        "E2341:E2368"), xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue. _
        Color = RGB(255, 199, 206) ' 192, 0, 0 dark red, 198, 239, 206 light green, 79, 98, 40 dark green
    ActiveWorkbook.Worksheets("Sheet24 (4)").Sort.SortFields.Add(Range( _
        "F2341:F2368"), xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue. _
        Color = RGB(255, 199, 206)
    ActiveWorkbook.Worksheets("Sheet24 (4)").Sort.SortFields.Add(Range( _
        "G2341:G2368"), xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue. _
        Color = RGB(255, 199, 206)
    ActiveWorkbook.Worksheets("Sheet24 (4)").Sort.SortFields.Add(Range( _
        "H2341:H2368"), xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue. _
        Color = RGB(255, 199, 206) ' light red
    ActiveWorkbook.Worksheets("Sheet24 (4)").Sort.SortFields.Add(Range( _
        "I2341:I2368"), xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue. _
        Color = RGB(255, 199, 206)
    ActiveWorkbook.Worksheets("Sheet24 (4)").Sort.SortFields.Add(Range( _
        "J2341:J2368"), xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue. _
        Color = RGB(192, 0, 0) ' dark red
    ActiveWorkbook.Worksheets("Sheet24 (4)").Sort.SortFields.Add(Range( _
        "K2341:K2368"), xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue. _
        Color = RGB(192, 0, 0)
    ActiveWorkbook.Worksheets("Sheet24 (4)").Sort.SortFields.Add(Range( _
        "L2341:L2368"), xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue. _
        Color = RGB(192, 0, 0)
    ActiveWorkbook.Worksheets("Sheet24 (4)").Sort.SortFields.Add(Range( _
        "M2341:M2368"), xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue. _
        Color = RGB(192, 0, 0)
    ActiveWorkbook.Worksheets("Sheet24 (4)").Sort.SortFields.Add(Range( _
        "N2341:N2368"), xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue. _
        Color = RGB(192, 0, 0)
    ActiveWorkbook.Worksheets("Sheet24 (4)").Sort.SortFields.Add(Range( _
        "O2341:O2368"), xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue. _
        Color = RGB(192, 0, 0)
    ActiveWorkbook.Worksheets("Sheet24 (4)").Sort.SortFields.Add(Range( _
        "P2341:P2368"), xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue. _
        Color = RGB(192, 0, 0)
    ActiveWorkbook.Worksheets("Sheet24 (4)").Sort.SortFields.Add(Range( _
        "Q2341:Q2368"), xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue. _
        Color = RGB(255, 199, 206)
    ActiveWorkbook.Worksheets("Sheet24 (4)").Sort.SortFields.Add(Range( _
        "R2341:R2368"), xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue. _
        Color = RGB(255, 199, 206)
    With ActiveWorkbook.Worksheets("Sheet24 (4)").Sort
        .SetRange Range("A2341:Y2368")
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

Open in new window


Can a loop shorten the number of lines of code ?
VBA

Avatar of undefined
Last Comment
Bill Prew

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Bill Prew

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
vbaabv

ASKER
Hi Bill,
     Thank you very much. This helps very much.
 
      I would like to be able to do these sorts as quickly as possible without having to edit a lot in the code every time a different section of the worksheet is being sorted, so I have modified your code to try to go in that direction.  

     The modified code below will sort the reds in ascending and the greens in descending order all at the same time. Also, I have tried to add Input boxes to get the row numbers to work on (so this would not have to be re-typed every time the rows being sorted change) and also the name of the worksheet and tried to implement these in-puted variables into the code, but I am not sure how these things work in VBA.  

Sub ColorSort()
'
' ColorSort Macro

    Dim startRowNum As Integer
    Dim endRowNum As Integer
    Dim wksname As String
    
    startRowNum = InputBox("Enter beginning row number")
    endRowNum = InputBox("Enter ending row number")
    wksname = InputBox("Enter name of worksheet")

    Range("A{startRowNum}:Y{endRowNum").Select 'need for changing row numbers
    
            With ActiveWorkbook.Worksheets("wksname").Sort

        .SortFields.Clear
        .SortFields.Add Key:=Range("D{startRowNum}:D{endRowNum}"), SortOn:=xlSortOnCellColor, Order:=xlAscending, DataOption:=xlSortNormal '  change Ascending or Descending ; need for changing row numbers

        For lngColumn = Asc("D") To Asc("R")
            If lngColumn >= Asc("J") And lngColumn >= Asc("N") Then ' Can also use only one column
                lngColor = RGB(255, 199, 206) ' light red
            Else
                lngColor = RGB(192, 0, 0) ' dark red
            End If
            .SortFields.Add(Range(Chr(lngColumn) & "startRowNum:" & Chr(lngColumn) & "endRowNum"), xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue.Color = lngColor ' change Ascending or Descending 'need for changing row numbers
        Next

        .SetRange Range("A{startRowNum}:Y{endRowNum}") ' need for changing row numbers
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
        
    End With
    
     With ActiveWorkbook.Worksheets("test").Sort

        .SortFields.Clear
        .SortFields.Add Key:=Range("D{startRowNum:D{endRowNum}"), SortOn:=xlSortOnCellColor, Order:=xlDescending, DataOption:=xlSortNormal ' range needs to change row numbers ; change Ascending or Descending
          
            For lngColumn = Asc("D") To Asc("R")
            If lngColumn >= Asc("J") And lngColumn >= Asc("P") Then ' Can use only one column
                lngColor = RGB(198, 239, 206) ' light green
            Else
                lngColor = RGB(79, 98, 40) ' dark green
            End If
            .SortFields.Add(Range(Chr(lngColumn) & "startRowNum:" & Chr(lngColumn) & "endRowNum"), xlSortOnCellColor, xlDescending, , xlSortNormal).SortOnValue.Color = lngColor ' change Ascending or Descending 'needs to change row numbers
        Next
        
        .SetRange Range("A{startRowNum}:Y{endRowNum}") ' needs to change row numbers
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    
End Sub

Open in new window

parkhill04

Hi Bill,
     
      Thank you again for your time and help. (By the way I have two logins, so I am vbaabv and parkhill04).
       I have uploaded a Excel worksheet that is a truncated sheet of what I am working on.  Rows 2 - 362 of this sheet have been manually sorted with three separate sorts and provide and idea of what I am getting after.

      I tried sorting rows 365 - 519 (basically BINCODE 20 and 20.1 [Column U]) in the uploaded Excel worksheet with your new approach, but it did not really result in what I am looking for. The rows still look pretty random after sorting (compare with manually sorted rows 2-169, 161-251, 253-362)

      (The worksheet I am working on has 20,800 rows with 35 bins (more with sub-bins), so that is a lot of sorting and why I am looking for a quick way to get the sorting done.)
cluster_example.xlsx
vbaabv

ASKER
Hi Bill,
     
      Thank you again for your time and help.

       I have uploaded a Excel worksheet that is a truncated sheet of what I am working on.  Rows 2 - 362 of this sheet have been manually sorted with three separate sorts and provide and idea of what I am getting after.

      I tried sorting rows 365 - 519 (basically BINCODE 20 and 20.1 [Column U]) in the uploaded Excel worksheet with your new approach, but it did not really result in what I am looking for. The rows still look pretty random after sorting (compare with manually sorted rows 2-169, 161-251, 253-362) and the sorting seems to work better with the original code that I modified.

      (The worksheet I am working on has 20,800 rows with 35 bins (more with sub-bins), so that is a lot of sorting and why I am looking for a quick way to get the sorting done.)
cluster_example.xlsx
Your help has saved me hundreds of hours of internet surfing.
fblack61
vbaabv

ASKER
I have now modified my program to two parts. The below code, part I, makes a pop-up input box that asks for worksheet name and range.

Option Explicit

Sub Test()
    Dim oRangeSelected As Range
    If SelectARange("Please select a range of cells!", "SelectARAnge Demo", oRangeSelected) = True Then
        MsgBox "You selected:" & oRangeSelected.Address(, , , True)
    Else
        MsgBox "You cancelled"
    End If
End Sub

Function SelectARange(sPrompt As String, sCaption As String, oReturnedRange As Range) As Boolean
    Dim frmSelectCells As ufSelectCells
    Set frmSelectCells = New ufSelectCells
    With frmSelectCells
        .PromptText = sPrompt
        .CaptionText = sCaption
        If TypeName(Selection) = "Range" Then
            .StartAddress = Selection.Address(External:=True)
        End If
        .Initialise
        .Show
        If .OK Then
            Set oReturnedRange = .ReturnedRange
            If oReturnedRange Is Nothing Then
                SelectARange = False
            Else
                SelectARange = True
            End If
        Else
            SelectARange = False
        End If
    End With
    
    Unload frmSelectCells
    Set frmSelectCells = Nothing
    
End Function

Open in new window


The above code works fine, but only produces a pop-up box showing the range selected. I would like the above code to pass along the worksheet name and range to the code below, part 2, which is a modification of what Bill Prew wrote for me earlier in this post.

Sub ColorSort()
'
' ColorSort Macro
	
	On Error Resume Next 
    Dim rngInput As Range 
    Set rngInput = Application.InputBox(Prompt:="Select range or enter A1 notation:", Type:=8) 
    If Not rngInput Is Nothing Then 
    End If

    Range("A2341:Y2440").Select 
    
    With ActiveWorkbook.Worksheets("test").Sort

        .SortFields.Clear
        .SortFields.Add Key:=Range("D2341:D2440"), SortOn:=xlSortOnCellColor, Order:=xlAscending, DataOption:=xlSortNormal '  change Ascending or Descending ; need for changing row numbers

        For lngColumn = Asc("D") To Asc("R")
            If lngColumn >= Asc("J") And lngColumn >= Asc("N") Then ' Can also use only one column
                lngColor = RGB(255, 199, 206) ' light red
            Else
                lngColor = RGB(192, 0, 0) ' dark red
            End If
            .SortFields.Add(Range(Chr(lngColumn) & "startRowNum:" & Chr(lngColumn) & "endRowNum"), xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue.Color = lngColor 
        Next

        .SetRange Range("A2341:Y2440") 
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
        
    End With
    
     With ActiveWorkbook.Worksheets("test").Sort

        .SortFields.Clear
        .SortFields.Add Key:=Range("D{startRowNum:D{endRowNum}"), SortOn:=xlSortOnCellColor, Order:=xlDescending, DataOption:=xlSortNormal         
            For lngColumn = Asc("D") To Asc("R")
            If lngColumn >= Asc("J") And lngColumn >= Asc("P") Then 
                lngColor = RGB(198, 239, 206) ' light green
            Else
                lngColor = RGB(79, 98, 40) ' dark green
            End If
            .SortFields.Add(Range(Chr(lngColumn) & "startRowNum:" & Chr(lngColumn) & "endRowNum"), xlSortOnCellColor, xlDescending, , xlSortNormal).SortOnValue.Color = lngColor 
        Next
        
        .SetRange Range("A2341:Y2440") 
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    
End Sub

Open in new window


    I would like to connect the above two parts.That is, use the input box to select a worksheet and a range that is passed to the ColorSort code and execute the ColorSort code using the worksheet and range passed in by the input box.
Bill Prew

Where does ufSelectCells come from, I see it referenced in the code you posted but am not familiar with that object?

    Dim frmSelectCells As ufSelectCells
    Set frmSelectCells = New ufSelectCells

Open in new window


»bp
Bill Prew

@vbaabv,

It looks like you got a paid solution  per the link below, so I assume you are all set with this?


Since your initial question was answered by my earlier solution post, could you consider accepting that and getting this question closed?  If you don't think my solution was helpful to the original question then go ahead and delete this question.  Either way if you could follow up and act on closing this question now that you are all set it would be helpful


»bp
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.