2014-05-08 26 views
3

我有一個交替背景的excel文件,以提高可讀性。排序在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) 
[...] 

有沒有一種辦法,而不風格內容進行排序被複制:在Backgroundstyle也與內容,這破壞像交替的風格感動?

+0

是否可以在完成排序後重新應用樣式?既然你有一個VBA宏,那將是相對微不足道的。 – Floris

+1

使用條件格式或表/表? – pnuts

+2

在http://stackoverflow.com/q/16274258/1967396看到一些有用的討論 - 這是同一個問題(或多或少),但我不確定你會接受一個答案,所以我沒有投票「close as duplicate」 – Floris

回答

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)pasteformats(range, formats),這將使代碼更加模塊化和可讀。這將封裝我在一個簡單的包裝中添加的上面的一些行,以便您的原始代碼只需要兩行(以及輔助模塊中的兩個函數)。

+1

看起來很有希望。將嘗試 –