VBA-对引用MergeArea的单元格进行排序

时间:2018-06-28 13:15:21

标签: excel vba excel-vba excel-2013

我的排序代码遇到问题。我的目标是按地址类型对区域进行排序。每个人都有多个帐户,只要有帐户,名称就会出现在合并区域中。因此,将“ B3:B6”中的第一个合并。

但是,有时这些人在每个帐户下都有不同的地址。因此,我想按E列中的值对每个区域(在本例中为“ C3:H6”)进行排序。但是,当我逐行运行时,它不会执行。

代码:

With NeedMail
    rwCnt = .Cells(Rows.Count, 1).End(xlUp).Row
    For y = 3 To rwCnt
        If .Cells(y, 2).MergeCells Then
            Set mrg = .Range(.Cells(y, 2).MergeArea.Address)
            Set srt = .Range(mrg.Offset(0, 1).Address & ":" & mrg.Offset(0, 6).Address)
            Set keyRng = .Range(mrg.Offset(0, 3).Address)
            cnt = .Cells(y, 2).MergeArea.Rows.Count
            Z = y + cnt - 1

            .Sort.SortFields.Clear
            .Sort.SortFields.Add Key:=keyRng, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
            With .Sort
                .SetRange srt
                .Header = xlNo
                .MatchCase = False
                .Orientation = xlTopToBottom
                .SortMethod = xlPinYin
                .Apply
            End With

            mrg.UnMerge

        'More code to execute here

        End If
    Next y
End With

样品数据:

SAMPLE DATA

在此先感谢您,我一直在绞尽脑汁想弄清楚出什么问题了?

1 个答案:

答案 0 :(得分:1)

当您偏移mrg时,例如Set srt = .Range(mrg.Offset(0, 1)...,您的新偏移范围只有1行高。因此,Resize使用cnt的行数。

此外,一旦拥有srt,就可以使用srt.Sort。 这是修改后的代码,显示了简化的排序。

Sub SortWhenMerged()
    Dim needMail As Worksheet
    Dim rwCnt As Long, y As Long, cnt As Long
    Dim mrg As Range, srt As Range, keyRng As Range

    Set needMail = ThisWorkbook.Worksheets("NeedMail")
    With needMail
        rwCnt = .Cells(.Rows.Count, 1).End(xlUp).row

        For y = 3 To rwCnt
            If .Cells(y, 2).MergeCells Then

                Set mrg = .Cells(y, 2).MergeArea
                cnt = mrg.Rows.Count

                Set srt = mrg.Offset(, 1).Resize(cnt, 6)
                Set keyRng = mrg.Offset(, 3).Resize(cnt)

                srt.Sort Key1:=keyRng, Order1:=xlAscending, Header:=xlNo, Orientation:=xlTopToBottom, SortMethod:=xlPinYin

                mrg.UnMerge
            End If
        Next y
    End With

End Sub