双击标题可对合并的单元格VBA进行排序

时间:2018-12-07 21:53:17

标签: excel vba excel-vba

我有一张工作表,其中有第4行中各列的标题。我有一个代码,当我双击第4行中的某个单元格时,它将按该单元格对数据进行排序。我现在遇到的问题是在B列中,单元格与下面的行合并。因此,例如第4行和第5行已合并,第6行和第7行等。由于这些合并的单元格,我拥有的代码将不再让我排序。有人可以帮忙吗?

这是我正在使用的代码

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

lr = Cells(Rows.Count, "B").End(xlUp).row
lc = Cells(4, Columns.Count).End(xlToLeft).Column
If Target.row = 4 And Target.Column <= lc Then Range(Cells(4, "B"), Cells(lr, lc)).Sort Key1:=Cells(4, Target.Column), Header:=xlYes 'Order1:=xlDescending

End Sub

根据要求提供我的工作表Sheet

的图片

1 个答案:

答案 0 :(得分:0)

尝试

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    Dim lc As Integer
    lc = Cells(4, Columns.Count).End(xlToLeft).Column
    If Target.Row = 4 And Target.Column <= lc Then
        sortdescent Target.Column - 1, lc
    End If
End Sub

模块代码

Sub sortdescent(x As Integer, col As Integer)
    Dim vDB
    Dim strTemp()
    Dim r As Integer, c As Integer, i As Integer, j As Integer
    Dim m As Integer

    ReDim strTemp(1 To 2, 1 To col)
    vDB = Range("b5", Cells(Range("c" & Rows.Count).End(xlUp).Row, col))
    r = UBound(vDB, 1)
    c = UBound(vDB, 2)


    For i = 1 To r Step 2
        For j = 1 To r Step 2
            'If vDB(j, x) > vDB(i, x) Then 'Ascent
            If vDB(j, x) < vDB(i, x) Then 'Descent

                For m = 1 To c
                    strTemp(1, m) = vDB(i, m)
                    strTemp(2, m) = vDB(i + 1, m)
                    vDB(i, m) = vDB(j, m)
                    vDB(i + 1, m) = vDB(j + 1, m)
                    vDB(j, m) = strTemp(1, m)
                    vDB(j + 1, m) = strTemp(2, m)
                Next
            End If
        Next j
    Next i
    Range("b5").Resize(r, c) = vDB
End Sub