2021年2月2日 星期二

VBA:排序;SORT

 這超級常被使用到的。

完整參數參MSDN:SORT

一般資料排序:降/升:xlDescending/xlAscending

    A_COUNT = ACTIVESHEET.Range("A2000").End(xlUp).Row

    ActiveSheet.Range("A1:Z" & A_COUNT).Sort Key1:=ActiveSheet.Range("A1"), Order1:=xlDescending, Header:=xlYes, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, SortMethod _

    :=xlStroke, DataOption1:=xlSortNormal



顏色排序:

MSDN有提供一個例子,小編以MSDN的例子做說明;首先 把C行對應儲存格的顏色代號(ColorIndex;沒顏色則為-4142),都列出後,標上標題(名稱為index),再用C行的數字做排序完成後,在清除C行資料。

Sub ColorSort()
'Set up your variables and turn off screen updating.
Dim iCounter As Integer
Application.ScreenUpdating = False '關閉螢幕更新
'For each cell in column A, go through and place the color index value of the cell in column C.
For iCounter = 2 To 55 '寫2到55 的顏色colorindex號碼
Cells(iCounter, 3) = _
Cells(iCounter, 1).Interior.ColorIndex
Next iCounter
'Sort the rows based on the data in column C
Range("C1") = "Index" '標題寫入
'以下為排序
Columns("A:C").Sort key1:=Range("C2"), _
order1:=xlAscending, header:=xlYes
'Clear out the temporary sorting value in column C, and turn screen updating back on.
'清除第三行資料。
Columns(3).ClearContents
Application.ScreenUpdating = True '開啟螢幕更新
End Sub
view raw ColorSort hosted with ❤ by GitHub


這MSDN的這個方法有很多好處歐,因為一般手動顏色排序都是一個 KEY值指定一種顏色,要多顏色實在是要設定很多(有興趣可以自己錄錄巨集,CODE會很嚇人),真要說缺點就是要多一行做資料存放。

沒有留言:

張貼留言

指數變化(2025.03.28)

 指數變化(2025.03.28) 上周焦點: 美國消費者信心指數 3/25 92.9 美國耐久財訂單月增率 3/26 1.4 PCE 月增 0.4 年增 2.8 (不多阿,最高還有5.5ㄝ)   本周愛看: 美國非農業就業人數變化 美國ISM製造業採購經理人指數 美國芝加哥FE...