最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

excel - How to keep rows with the same value in a column together when sorting - Stack Overflow

programmeradmin0浏览0评论

I'm coding a larger project that will automatically sort a table ("Table2") by the values in different columns, but I want to create an exception where rows with the same value in column D are always kept next to each other. There's definitely multiple issues with what I have written but it's a starting point. Rows Dim grpRange As String: grpRange = "A"&first&":J"&last and Rows(first:last).Group are currently showing up as red and when run, I'm getting a compile error the first time Rows(firstPos).Insert tries to run, and I'm getting an error that the program is running out of stack space.

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("D3:D2000")) Is Nothing Then
        With Sheets("Sheet1")
            Dim wo As String
            Dim tb2 As ListObject
            Set tb2 = .ListObjects("Table2")
            Dim dupes() As Variant
            Dim t As Integer: t = 0
            Dim count As Integer: c = 2
            Dim newPos As Integer
            Dim Occurrences As Integer
            For Each rw In tb2.DataBodyRange.Rows    ' Iterate through each element.
                count = count + 1
                If rw.Cells(4).Value = ActiveCell.Value Then
                    If Occurrences = 0 Then
                        Occurrences = Occurrences + 1
                        Dim firstPos As Integer: firstPos = rw.Cells(4).Row
                    Else
                        Occurrences = Occurrences + 1
                        Rows(count).Cut
                        Rows(firstPos).Insert
                        newPos = firstPos - 1
                        ReDim dupes(0 To t)
                        dupes(t) = Rows(newPos).Row
                        t = t + 1
                    End If
                End If

                If Occurrences > 1 Then
                    Dim first As Integer: first = dupes(0)
                    Dim last As Integer: last = dupes(t)
                    Dim grpRange As String: grpRange = "A"&first&":J"&last
                    Rows(first:last).Group
                End If
            Next
        End With
    End If
End Sub

Is trying to group the rows like this even the right approach?

EDIT: Th reason why I'm not just sorting by Column D is that what the end user wants is the table to be auto-sorted by column c as primary and column e as secondary (this code is already implemented and works fine), however sometimes there are multiple rows with the same values in column D (for context it's the order #) but different values in Column E and he wants those kept together. The problem with just sorting col C>col D>col E is that the sorting in col E would then be totally messed up for all of the entries with no duplicates in column D.

发布评论

评论列表(0)

  1. 暂无评论