【发布时间】:2021-11-27 21:35:24
【问题描述】:
此 VBA 代码通过双击列标题按任意列对我的黑胶唱片收藏目录进行排序。
在我的古典黑胶唱片中,将近一半的歌曲标题都用引号引起来,因此当对该列进行排序时,它会按字母顺序对标题进行排序, 先是引号,然后是标题没有 em> 引号。
有没有办法添加一行代码,以便在排序时忽略前导引号,使"ac" 出现在ab 之后等等?
我现在的解决方法是使用隐藏的帮助列来去除引号,但我希望有一个更简洁的解决方案。
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim KeyRange As Range
Dim ColumnCount As Integer
'Clear previous sorts
ActiveSheet.Sort.SortFields.Clear
'Clear contents of hidden helper column
Columns("K").ClearContents
'Copy and Paste songname column to helper column
Range("F:F").Copy Range("K:K")
'Strip quotes from helper column
Application.ScreenUpdating = FALSE
ActiveSheet.Columns("K").Replace What:="""", Replacement:="", LookAt:=xlPart, MatchCase:=False
Application.ScreenUpdating = TRUE
'Set range of header columns that will sort on double-click
ColumnCount = Range("A1:J1").Columns.Count
Cancel = FALSE
If Target.Row = 1 And Target.Column <= ColumnCount Then
Cancel = TRUE
'Get cell address of double-clicked header cell
Set SortColumn = Range(Target.Address)
'Set fill color of currently sorted column header
Rows(1).Interior.Color = xlNone
SortColumn.Interior.ColorIndex = 15
With ActiveSheet
'Sort by hidden column if songname column is double-clicked
If SortColumn = Range("F1") Then
Range("K1").Select
Else
SortColumn.Select
End If
'Sort by selected column followed by album, disc, then track
.Sort.SortFields.Add Key:=Selection, _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.Sort.SortFields.Add Key:=Range("E1"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.Sort.SortFields.Add Key:=Range("B1"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.Sort.SortFields.Add Key:=Range("C1"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
End With
With ActiveSheet.Sort
'Set flexible sort range to all data before reaching entirely empty row or column
.SetRange Range("A1").CurrentRegion
.Header = xlYes
.MatchCase = FALSE
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End If
End Sub
【问题讨论】:
-
不幸的是,这不仅仅是一行代码。
-
您能详细说明一下吗?为我指明正确的方向?
-
为什么不删除所有的
",一个简单的查找/替换就可以了? -
含义 - 排序按字母顺序进行,引号按字母顺序排在第一位。没有简单的单线来做你想做的事。一种解决方法可能是去掉引号的帮助列。
-
@ScottCraner 我不想删除引号,因为它们应该存在,因为这些歌曲名称通常是戏剧作品或歌剧的标题,应该用引号引起来。
标签: excel vba sorting special-characters