简体   繁体   中英

Excel - Sorting a list with multiple rows per entry

Is there any way to sort a list in excel if the list is not 1 row per entry. The entries could be 2+ rows

Unsorted:

      A       B       C      

1   Entry3  
2            Data1  Data2  
3            Data3  Data4   
4   Entry1  
5            Data5  Data6  
6   Entry2 
7            Data7  Data8

Sorted:

      A       B       C      

1   Entry1  
2            Data5  Data6    
3   Entry2  
4            Data7  Data8  
5   Entry3 
6            Data1  Data2
7            Data3  Data4

You need a magic trick. ;)

For the Pledge , you first fill in the areas underneath each Entry with the duplicate of the header Entry . Basically, A1:A2 should have Entry1 , A3:A4 should have Entry2 , and A5:A7 should have Entry3 .

The following subroutine does the above.

Sub Pledge()
    Dim LRow As Long: LRow = Range("B" & Rows.Count).End(xlUp).Row
    Dim CurrentName As String
    CurrentName = ""
    For Iter = 1 To LRow
        If Range("A" & Iter).Value <> "" Then
            If Range("A" & Iter).Value <> CurrentName Then
                CurrentName = Range("A" & Iter).Value
            End If
        Else
            Range("A" & Iter).Value = CurrentName
        End If
    Next Iter
End Sub

Screenshot:

在此处输入图片说明

For the Turn , we just sort the ranges according to column A. This is fairly simple.

Sub Turn()
    Range("A:C").Sort Range("A1"), xlAscending
End Sub

Screenshot:

在此处输入图片说明

But it's never over, right? You don't clap yet, not until it's brought back. Here's the Prestige .

Sub Prestige()
    Dim LRow As Long: LRow = Range("B" & Rows.Count).End(xlUp).Row
    Dim CurrentName As String
    CurrentName = ""
    For Iter = 1 To LRow
        If Range("A" & Iter).Value <> "" Then
            If Range("A" & Iter).Value = CurrentName Then
                Range("A" & Iter).Value = ""
            Else
                CurrentName = Range("A" & Iter).Value
            End If
        End If
    Next Iter
End Sub

在此处输入图片说明

And there you go. Paste the above in a module and call one by one, or modify them yourself inside one subroutine. This part, I leave to you. :)

Sub GrandIllusion()
    Pledge
    Turn
    Prestige
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM