[英]In a multi-sheet workbook, how do I code a multi-column sort in VBA?
I'm building a cargo stacking calculator in Excel/VBA, and one stage of it separates the stackable cargo into a separate sheet for the actual stacking calculations. 我正在用Excel / VBA构建一个货物堆叠计算器,其中的一个阶段将可堆叠货物分离为单独的表,以进行实际的堆叠计算。 As part of that, I need to sort the items by, in order:
作为其中的一部分,我需要按以下顺序对项目进行排序:
Using the macro recorder to try with an Excel sort, it's all in A1 notation with no sheet defined. 使用宏记录器尝试使用Excel排序时,所有操作均以A1表示法进行,未定义工作表。 I've also tried adding a sheet variable (
wsStackList.
) to the Range element, to no avail. 我也尝试将工作表变量(
wsStackList.
)添加到Range元素,但无济于事。 Nor can I seem to make it work with R1C1 notation (tried with Cells(1,2):Cells(2,2)
and Cells(1,2), Cells(2,2)
but not yet any concatenated or code-based forms) or named ranges ( Range("StackingField")
). 我似乎也无法使其使用R1C1表示法(尝试使用
Cells(1,2):Cells(2,2)
和Cells(1,2), Cells(2,2)
但还没有任何串联或基于代码的表单)或命名范围( Range("StackingField")
)。
The error message I get at the moment is a 1004 error, specified as "Unable to get the Sort property of the Range class". 我目前收到的错误消息是1004错误,指定为“无法获取Range类的Sort属性”。
My current code for this sub is: 我当前为该子代码是:
Sub SegmentSort()
' Sort by segment
Range("StackingField").Sort.SortFields.Add Key:=Range("A2:A501"),_
SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:="Pipes,Beams,Plates",_
DataOption:=xlSortNormal
Range("StackingField").Sort.SortFields.Add Key:=Range("F2:F501"),_
SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
Range("StackingField").Sort.SortFields.Add Key:=Range("E2:E501"),_
SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With Range("StackingField").Sort
.SetRange Range("A1:H501")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.Apply
End With
End Sub
Is it worth trying to make this work, or would I be better off going back to basics and trying to code some sort of sort algorithm from scratch in VBA? 值得尝试进行这项工作,还是重新回到基础知识并尝试在VBA中从头开始编写某种排序算法更好呢? It's not something I have any experience of, but I know the basic concepts of swap sorts and the like.
我没有任何经验,但是我知道交换排序之类的基本概念。 Definitely far from confident.
绝对没有信心。
I don't know why Dirk Reichel deleted his answer, but it worked a treat! 我不知道为什么德克·赖切尔(Dork Reichel)删除了他的答案,但是这很有效! The code he suggested was this:
他建议的代码是这样的:
Sub SegmentSort()
With Sheets("Stacker").Sort
.SortFields.Clear
.SortFields.Add Range("A:A"), xlSortOnValues, xlAscending, "Pipes,Beams,Plates", xlSortNormal
.SortFields.Add Range("F:F"), xlSortOnValues, xlDescending, , xlSortNormal
.SortFields.Add Range("E:E"), xlSortOnValues, xlDescending, , xlSortNormal
.SetRange Range("A:H")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.Apply
End With
End Sub
Dirk, I can't give you the upvote you deserve, but thanks! 德克,我不能给你应得的支持,但谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.