2015-11-25 74 views
0

为什么这个工作:排序键范围查询

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 

话说

法范围失败

编辑

之所以问的是,我想那种关键是动态的,如:

Selection.Sort Key1:=Range(Cells(intRow, intCol)) 

我看不出如何做到这一点。

+0

因为'范围'本身并不意味着在这种情况下任何东西。尝试在你的第二行改变'Range(Cells(1,1)'到'Selection(Cells(1,1))'这并不是最佳实践,但至少你将'Cells'属性绑定到这个对象中最好的做法是始终限定您的范围,单元格,表单等 –

+0

感谢但选择提供了一种类型不匹配,我添加了一个编辑 – RGriffiths

+1

所以只需使用'Key1:= Cells(intRow,intCol)' –

回答

2

总是最好限定您正在使用哪些对象并直接使用对象,而不是使用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 
3

Cells呼叫已经返回Range对象,所以你应该使用

Selection.Sort Key1:=Cells(1,1), Order1:=xlAscending, Header:=xlNo, _ 
    OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _ 
    DataOption1:=xlSortNormal 

我认为你的困惑,是因为我们所产生的是通过两个单元的参数范围是有效的,即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 
看到自己这一点3210

您会收到一条消息,说明第一次msgbox调用的是3,但第二次尝试设置rng时会发生异常。至于为什么第二种格式不合法,我不知道。如果你发现开发者为什么以这种方式构建它,请告诉我们。

+0

谢谢。我添加了一个编辑来解释我想要做什么。我应该在开始时说。 – RGriffiths

+1

实际上,'Range(Cells(1,1))'相当于'Range(Cells( 1,1).Value)',因为它调用带有一个参数的Range的版本,并且期望一个有效的*范围地址*。所以如果单元格'A1'包含有效地址,例如“G5”,'Range Cells(1,1))'会指定单元格'G5'。 –

+1

@ASH谢谢你的揭秘! – DeanOC

2

之所以问的是,我想那种关键是动态...

问题中的至少一部分是依靠.Select和后续的Selection作为工作区域。如果您打算使用Range.CurrentRegion property(A1中的数据源“岛”),请使用With ... End With statement来定义.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 

我对“动态”的含义有点不清楚。以上将使用由.CurrentRegion定义的区域左上角的单元格。如果您使用With .Range("D5:H99"),则.Cells(1)将引用D5。

请参阅How to avoid using Select in Excel VBA macros以获取更多有关摆脱依赖选择和激活来实现您的目标的方法。