2017-10-18 254 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