我正在为 Excel 创建一个数据库。 目标是让数据输入到其中自动按颜色排序,然后按字母顺序排序。
我正在使用以下 VBA 进行自动排序。
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
If Not Intersect(Target, Range("A:A")) Is Nothing Then
Range("A1").Sort Key1:=Range("A2"), _
Order1:=xlAscending, Header:=xlYes, _
OrderCustom:=1, MatchCase:=False, _
Orientation:=xlTopToBottom
End If
End Sub
我已经设置了用于颜色排序的宏,如下所示:
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ActiveWorkbook.Worksheets("Master").ListObjects("Table2").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Master").ListObjects("Table2").Sort.SortFields.Add( _
Range("Table2[Name]"), xlSortOnCellColor, xlDescending, , xlSortNormal). _
SortOnValue.Color = RGB(255, 0, 0)
With ActiveWorkbook.Worksheets("Master").ListObjects("Table2").Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
问题是一旦我输入新数据,字母排序就会覆盖颜色排序。
有人可以帮我做一下,以便颜色排序覆盖字母顺序吗?
非常感谢任何帮助!
最佳答案
当您像这样直接设置 Range.Sort
属性时,它会删除现有的 SortFields
可选步骤:循环并删除 .SortOn
处的任何 SortFields
不是 SortOnCellColor
来删除任何非颜色排序
要在末尾添加排序,您只需添加一个新的 SortField
,就像您已经对颜色所做的那样,然后应用排序:
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
If Not Intersect(Target, Me.Range("A:A")) Is Nothing Then
'Add new SortField to end of existing Sorts
Me.ListObjects("Table2").Sort.SortFields.Add Key:=Me.Range("A2"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
'Apply new SortFields
Me.ListObjects("Table2").Sort.Apply
End If
End Sub
然后,检查并从代码的其余部分中删除对 ActiveWorkbook
的所有引用。
关于excel - 自动排序优先于颜色排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49881523/