我得到了一个带有交替背景的 Excel 文件,以提高可读性。
Row 1: White Background
Row 2: Gray Background
Row 3: White Backgrund
[...]
我使用 VBA 函数对 Excel 文件的内容进行排序,通过单击按钮引发该事件:
Sub SortByName()
ActiveSheet.Sort.SortFields.Clear
ActiveSheet.Sort.SortFields.Add Key:=Range("BO6:BO1024"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ActiveSheet.Sort.SortFields.Add Key:=Range("D6:D1024"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveSheet.Sort
.SetRange Range("A6:DD1024")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
排序效果很好,就像我想要的那样,但是背景样式也会随着内容移动,这会破坏交替样式,例如:
Row 1: White (was row 3)
Row 2: White (was row 1)
Row 3: Gray (was row 2)
[...]
有没有一种方法可以在不复制样式的情况下对内容进行排序?
我承认这是一个黑客行为,但下面的方法可以工作。它一次对一个单元格进行“修复格式” - 大概您可以更改此设置以对整行执行此操作
Sub sortNoFormat()
Dim r As Range
Dim f() ' a place to keep the formatting
Dim ii As Integer
Dim c
' set up the sort:
Set r = Range("tosort")
ActiveSheet.Sort.SortFields.Clear
ActiveSheet.Sort.SortFields.Add Key:=r, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
' before sorting, copy the format (color) of each cell to array f:
ReDim f(1 To r.Cells.Count)
ii = 1
For Each c In r.Cells
f(ii) = c.Interior.ColorIndex
ii = ii + 1
Next
' Perform the sort:
With ActiveSheet.Sort
.SetRange r
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
' apply the old formatting:
ii = 1
For Each c In r.Cells
c.Interior.ColorIndex = f(ii)
ii = ii + 1
Next
End Sub
我相信很容易看出如何创建几个辅助函数 -formats = copyFormats(range)
and pasteformats(range, formats)
这将使代码更加模块化和可读。这会将我上面添加的一些行封装在一个简单的包装器中,因此您的原始代码只需要两行(以及辅助模块中的两个函数)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)