2017-10-18 249 views
1

執行排序時出現上述錯誤。我完全限定了所有對象,並檢查了我的變量是否保存了正確的值。在第一行出現的錯誤:無法獲取Range類的Sort屬性

With ws.Columns("A:E").Sort 
    .SortFields.Clear 
    .SortFields.Add Key:=ws.Range("A2:A" & oldLastRow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal 
    .SetRange ws.Range("A1:E" & oldLastRow) 
    .Header = xlYes 
    .MatchCase = False 
    .Orientation = xlTopToBottom 
    .SortMethod = xlPinYin 
    .Apply 
End With 

它似乎並不無論我如何參考範圍內,每一項給出了同樣的錯誤:

With ws.Range("A:E").Sort 


With ws.Range("A1:E" & oldLastRow).Sort 

有數據在每個單元範圍和列都有標題。什麼可能導致這個問題?

回答

3

ws.Columns("A:E").Sort被調用RangeSort函數,它是從Sort類的工作表的不同:

enter image description here

(打F2在VBA編輯器獲得該屏幕)

所以如果你只是刪除你的代碼片段的.Columns("A:E"),你的代碼可能會工作:例如:

With ws.Sort 
    .SortFields.Clear 
    .SortFields.Add Key:=ws.Range("A2:A" & oldLastRow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal 
    .SetRange ws.Range("A1:E" & oldLastRow) 
    .Header = xlYes 
    .MatchCase = False 
    .Orientation = xlTopToBottom 
    .SortMethod = xlPinYin 
    .Apply 
End With 

你已經在說你想要用.SetRange ws.Range("A1:E" & oldLastRow)排序,所以你可以看到它在With語句中也有點多餘(以及產生錯誤)。

PS我得到

Run-time error '438': Object doesn't support this property or method