sorting键范围查询
为什么这个工作:
Range(Cells(1, 1), Cells(5, 5)).Select Selection.Sort Key1:=Range("A1"), Order1:=xlAscending, Header:=xlNo, _ OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _ DataOption1:=xlSortNormal
但是这不?
Range(Cells(1, 1), Cells(5, 5)).Select Selection.Sort Key1:=Range(Cells(1,1)), Order1:=xlAscending, Header:=xlNo, _ OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _ DataOption1:=xlSortNormal
说
方法范围失败
编辑
问的原因是,我想sorting键是dynamic的,如:
Selection.Sort Key1:=Range(Cells(intRow, intCol))
我看不到这是如何完成的。
总是最好限定你正在使用哪些对象,直接使用这些对象,而不是使用Selection
或Range
,因为它有时会导致意想不到的后果或者减慢你的代码。
尝试这个:
Dim ws as Worksheet Set ws = Sheets("Sheet1") ' replace with your sheet name 'assume you wrap this around a loop to move through intRow and intCol _ or set them in some other fasion With ws.Range(Cells(1,1), Cells(5,5) .Sort Key1:=.Cells(intRow, intCol), Order1:=xlAscending, Header:=xlNo, _ OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _ DataOption1:=xlSortNormal End With
Cells
调用已经返回一个Range对象,所以你应该使用
Selection.Sort Key1:=Cells(1,1), Order1:=xlAscending, Header:=xlNo, _ OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _ DataOption1:=xlSortNormal
我认为你的困惑是由于将两个单元格parameter passing给范围是有效的,即Range(Cells(1, 1), Cells(5, 5))
,但是仅传递一个单元格参数是无效的,即Range(Cells(1, 1))
您可以使用以下代码片段自行查看
Public Sub test() Dim rng As Range Set rng = Range(Cells(1, 1), Cells(3, 1)) MsgBox rng.Cells.Count Set rng = Range(Cells(1, 1)) MsgBox rng.Cells.Count End Sub
你会得到一个消息说第一个msgbox调用3,但你第二次尝试设置rng时会得到一个exception。
至于为什么第二种格式是无效的,我不知道。 如果你发现为什么开发者这样build立它,让我们知道。
问的原因是,我想sorting键是dynamic的…
至less部分问题依赖于.Select
和随后的Selection
作为工作区。 如果您的意图是使用Range.CurrentRegion属性 (A1中的数据源“岛”),则使用With … End With语句来定义.CurrentRegion并使用它。
with worksheets("Sheet1") `<~~ set the parent worksheet! with .Cells(1, 1).CURRRENTREGION `<~~ set the 'island' of data .cells.Sort Key1:=.cells(1), Order1:=xlAscending, Header:=xlNo, _ OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _ DataOption1:=xlSortNormal end with end with
我对“dynamic”的含义有点不清楚。 以上将使用由.CurrentRegion定义的区域左上angular的单元格。 如果您使用With .Range("D5:H99")
那么.Cells(1)
将引用D5。
请参阅如何避免使用Excel中的selectVBAmacros来获取更多的方法来摆脱依靠select和activate来实现您的目标。