在Excel保持风格sorting?

我有一个交替背景的excel文件,以便更好的可读性。

Row 1: White Background Row 2: Gray Background Row 3: White Backgrund [...] 

我使用VBA函数对Excel文件的内容进行sorting,通过单击button来引发事件:

 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 

sorting工作正常,就像我想要的,但Backgroundstyle也随着内容的移动,破坏了交替的风格,如:

 Row 1: White (was row 3) Row 2: White (was row 1) Row 3: Gray (was row 2) [...] 

有没有一种方法来sorting的内容没有被复制的样式?

我承认这是一个黑客,但下面的工作。 它一次只进行一个单元格的“修复格式化” – 大概你可以改变它来完成整行

 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 

我相信很容易看到如何创build一些辅助函数 – formats = copyFormats(range)pasteformats(range, formats) ,使代码更加模块化和可读。 这将封装我在上面添加一个简单的包装的一些行,所以你原来的代码只需要两行(和辅助模块中的两个函数)。