excel - 双击排序列是混合顺序
问题描述
我的数据在一列中显示名称,然后在其他列中显示不同的数字。当我双击标题单元格时,它会按降序对列进行排序。这可行,但是所有名称都不再与其值匹配,我不知道为什么。
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
解决方案
您没有在要排序的范围内包含名称列。
你有
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
推荐阅读
- sql-server - 我们可以在 SSIS 中从 string 或 char 数据类型转换为 int (或数字)吗
- haskell - 将 Int 与 Bool 的 dataType 匹配
- docker - 如何构建基于 nginx:alpine 的自定义容器,侦听 80 以外的端口?
- angular - Angular 7 单元测试依赖注入在 ngOnInit 中不起作用
- amazon-dynamodb - dynamoDB记录更新后如何返回项目
- node.js - 编译 Electron 应用程序后如何使用调试工具?(带电子锻造)
- php - if语句中的PHP错误?
- mysql - 在 Visual Studio 2017 中打开的数据库
- java - 计算从左上角到右下角的所有可能路径
- python - Geopy,检查城市,避免重复,熊猫