Sort/Arrange Rows based on Cell Value in Range VBA

crp

New Member
Joined
Jul 30, 2021
Messages
18
Office Version
  1. 365
Platform
  1. Windows
I have a series of data compiled into one excel sheet. The order of the data depends on each row's association to other rows, based on their LinkTo values. Below is an example of before, and how I need the data to be organized. I'd like for this to be automated in VBA.

Example Raw Data
IDCategoryLinkTo
1Fruit
2Onion4
3Apple1
4Vegetable
5Banana1
6Red Apple3

Example Desired Result
IDCategoryLinkTo
1Fruit
3Apple1
6Red Apple3
5Banana1
4Vegetable
2Onion4
 

Excel Facts

Convert text numbers to real numbers
Select a column containing text numbers. Press Alt+D E F to quickly convert text to numbers. Faster than "Convert to Number"
Give this a go.

Assumptions:
1. Data has headers in row 1
2. Data begins in A2

VBA Code:
Sub LinkSort()
    Dim lRow As Long, m As Long
    Dim r As Range
    Dim ws As Worksheet
       
    Set ws = ActiveSheet
   
    lRow = Cells(Rows.Count, 1).End(xlUp).Row
   
    Set r = Range(Cells(2, 1), Cells(lRow, 3))
   
    With ws
        .Sort.SortFields.Clear
        .Sort.SortFields.Add2 Key:=Range("C2:C" & lRow) _
        , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        With .Sort
            .SetRange r
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
    End With
   
    Set r = Range(Cells(2, 1), Cells(lRow, 1))
   
    While Cells(2, 3).Value <> ""
        m = Application.Match(Cells(2, 3).Value, r, 0) + 2
        Rows("2:2").Cut
        Rows(m & ":" & m).Insert Shift:=xlDown
    Wend
   
End Sub
 
Upvote 0
Give this a go.

Assumptions:
1. Data has headers in row 1
2. Data begins in A2

VBA Code:
Sub LinkSort()
    Dim lRow As Long, m As Long
    Dim r As Range
    Dim ws As Worksheet
    
    Set ws = ActiveSheet
 
    lRow = Cells(Rows.Count, 1).End(xlUp).Row
 
    Set r = Range(Cells(1, 1), Cells(lRow, 3))
 
    With ws
        .Sort.SortFields.Clear
        .Sort.SortFields.Add2 Key:=Range("C2:C" & lRow) _
        , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        With .Sort
            .SetRange r
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
    End With
 
    Set r = Range(Cells(2, 1), Cells(lRow, 1))
 
    While Cells(2, 3).Value <> ""
        m = Application.Match(Cells(2, 3).Value, r, 0) + 2
        Rows("2:2").Cut
        Rows(m & ":" & m).Insert Shift:=xlDown
    Wend
 
End Sub
slight change to the code Set r = Range(Cells(1, 1), Cells(lRow, 3)) Need to include the headers in the initial range for sorting.
 
Upvote 0
I think it's close, but it isn't quite working for my dataset. For my data, there are 24 columns of information A:X. The LinkTo column is N, and it is referencing column A (ID). I should've mentioned before that it's possible for some cells in the N column to have multiple links. I'm not sure how that may change the code.
 
Upvote 0
Unfortunately I can't provide the actual data, but the example attached illustrates the same format. I've expanded the raw data tab a little, which is a similar layout to my data. The Desired Layout tab is what I'm trying to achieve. Note that since the tomato was tagged for both categories, it was copied and placed twice in the spreadsheet. The end state is that the resulting spreadsheet will depict traceability through the category hierarchy.

Thank you for your help so far.

Raw Data
Raw Data.PNG


Desired Layout
Desired Layout.PNG
 
Upvote 0
Is there a delimiter between the LinkTo ID's when there are more than one or is it just a space or new line?
 
Upvote 0
Please test this

VBA Code:
Sub LinkSort()
    Dim lRow As Long, m As Long, n As Long, i As Long
    Dim r As Range
    Dim wb As Workbook
    Dim str As String, replaced As String, Lnks As String
    
    Set ws = ActiveSheet
    
    lRow = Cells(Rows.Count, 1).End(xlUp).Row
    
    Set r = Range(Cells(1, 1), Cells(lRow, "N"))
    
    With ws
        .Sort.SortFields.Clear
        .Sort.SortFields.Add2 Key:=Range("N2:N" & lRow) _
        , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        With .Sort
            .SetRange r
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
    End With
    
    Set r = Range(Cells(2, 1), Cells(lRow, 1))
    
    While Cells(2, "N").Value <> ""
        str = Cells(2, "N").Value
        replaced = Replace(str, "-", "")
        n = Len(str) - Len(replaced)
        If n <= 1 Then
            m = Application.Match(Cells(2, "N").Value, r, 0) + 2
            Rows("2:2").Cut
            Rows(m & ":" & m).Insert Shift:=xlDown
            If m > r.Rows.Count Then
                Set r = Range(Cells(2, 1), Cells(Cells(Rows.Count, 1).End(xlUp).Row, 1))
            End If
        Else
            Rows("2:2").Copy
            Rows("3:" & 3 + n - 2).Insert Shift:=xlDown
            Application.CutCopyMode = False
            Set r = Range(Cells(2, 1), Cells(lRow + n - 1, 1))
            Lnks = Cells(2, "N").Value
            For i = 0 To n - 1
                j = InStr(i + 5, Lnks, "-", vbTextCompare)
                m = Application.Match(Mid(Lnks, j - 4, 6), r, 0) + 2
                Rows("2:2").Cut
                Rows(m & ":" & m).Insert Shift:=xlDown
                If m > r.Rows.Count Then
                    Set r = Range(Cells(2, 1), Cells(Cells(Rows.Count, 1).End(xlUp).Row, 1))
                End If
            Next i
        End If
    Wend
    
End Sub
 
Upvote 0
Yes this worked on the example data, thank you. Which variable needs to be adjusted if the rows are colored? After I ran it, it appeared columns O through X did not adjust.

Test Result.PNG
 
Upvote 0

Forum statistics

Threads
1,215,963
Messages
6,127,960
Members
449,412
Latest member
montand

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top