2015-11-25 70 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以獲取更多有關擺脫依賴選擇和激活來實現您的目標的方法。