首页 > 解决方案 > 双击排序列是混合顺序

问题描述

我的数据在一列中显示名称,然后在其他列中显示不同的数字。当我双击标题单元格时,它会按降序对列进行排序。这可行,但是所有名称都不再与其值匹配,我不知道为什么。

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

Dim KeyRange As Range
Dim ColumnCount As Integer
Dim lrow As Long

lrow = Sheets("Tracker").Cells(Rows.Count, "B").End(xlUp).Row

On Error Resume Next

    ColumnCount = Range("B5:Q" & lrow).Columns.Count
        Cancel = False
    If Target.Row = 5 And Target.Column <= ColumnCount Then
        Cancel = True
        Worksheets("Backend").Range("C1") = Target.Value

        Set KeyRange = Range(Target.Address)

        Range("B5:Q" & lrow).sort Key1:=KeyRange, Header:=xlYes, Order1:=xlDescending
        Worksheets("Backend").Range("A1") = Target.Column
        Worksheets("Backend").Calculate
            For i = 1 To ColumnCount
            Range("B5:Q" & lrow).Cells(1, i).Value = Worksheets("Backend").Range("A4").Offset(0, i - 1).Value
            Next i
    End If

On Error GoTo 0

End Sub

标签: excelvba

解决方案


您没有在要排序的范围内包含名称列。

你有

Range("B5:Q" & lrow).sort Key1:=KeyRange, Header:=xlYes, Order1:=xlDescending

但应该是

Range("A5:Q" & lrow).sort Key1:=KeyRange, Header:=xlYes, Order1:=xlDescending


编辑1:

由于名称在 B 列中,而不是我假设的 A 列,因此可能会相互应用多个排序。要消除这种可能性,请尝试使用工作表对象而不是范围对象进行排序(清除旧排序后)。

这是如何

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

    Dim KeyRange As Range
    Dim ColumnCount As Integer
    Dim lrow As Long

    lrow = Sheets("Tracker").Cells(Rows.Count, "B").End(xlUp).Row

    On Error Resume Next

    ColumnCount = Range("B5:Q" & lrow).Columns.Count
    Cancel = False
    If Target.Row = 5 And Target.Column <= ColumnCount Then
        Cancel = True

        Worksheets("Backend").Range("C1") = Target.Value

        With Me
            .Sort.SortFields.Clear
            .SortFields.Add2 Key:=Target, SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
            .Sort.SetRange .Range("B5:Q" & lrow)
            .Sort.Header = xlYes
            .Sort.MatchCase = False
            .Sort.Orientation = xlTopToBottom
            .Sort.SortMethod = xlPinYin
            .Sort.Apply
        End With


        With Worksheets("Backend")
            .Range("A1") = Target.Column
            .Calculate
            For i = 1 To ColumnCount
                Range("B5:Q" & lrow).Cells(1, i).Value = .Range("A4").Offset(0, i - 1).Value
            Next i
        End With

    End If

    On Error GoTo 0

End Sub

推荐阅读