我偶爾會使用 VBA,但我陷入了圍繞范圍的語法中。我想在活動作業表上選擇一個陣列,并一次對每一列進行排序,回傳一個有序列的陣列。for回圈似乎很簡單,但是,我不斷收到我認為與范圍有關的錯誤。
Public Sub Sortrange() 'sorts each column in a range individually low to high
Dim Rng, Sortcol As Range
HH = Selection.Rows.Count
Set Rng = Selection
Srow = Rng(1).Row
SCol = Rng(1).Column
With Rng
For i = 1 To .Columns.Count
A = Srow
B = SCol i - 1
Sortcol = Range(Cells(A, B), Cells(HH, B))
Sortcol.Sort key1:=Range(Cells(A, B))
Next
End With
End Sub
uj5u.com熱心網友回復:
Public Sub Sortrange() 'sorts each column in a range individually low to high
Dim Rng, Sortcol As Range
Dim Srow As Integer, Scol As Integer
Dim A, B, i As Integer
Set Rng = Selection
Dim selRows As Long: selRows = Rng.Rows.Count
Dim selCols As Long: selCols = Rng.Columns.Count
Srow = Rng(1).Row
Scol = Rng(1).Column
With Rng
For i = 1 To selCols
A = Srow
B = Scol i - 1
Set Sortcol = Range(Cells(A, B), Cells(selRows 1, B))
' Sort Column
ActiveSheet.Sort.SortFields.Clear
ActiveSheet.Sort.SortFields.Add2 Key:=Sortcol _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortTextAsNumbers
With ActiveSheet.Sort
.SetRange Sortcol
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Next
End With
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/346060.html
