问题
I'm trying to write a code that will remove duplicates from my list.
It worked well on my mac, but when I tried to run it on windows I got the runtime error 438:
object doesn't support this property or method.
What went wrong?
Range("E2:E150").Select
ActiveWorkbook.Worksheets("NOS").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("NOS").Sort.SortFields.Add2 Key:=Range("E2"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("NOS").Sort
.SetRange Range("E2:G150")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.Apply
End With
Range("E1").Select
End Sub
回答1:
The issue is that you probably use an Excel version released before 2016. The .SortFields.Add2 method was introduced in 2016 if your Excel is older you must use the old .SortFields.Add method (which lacks the ability of using the SubField parameter).
You might benefit from reading How to avoid using Select in Excel VBA, your .Select statements are pretty useless and not needed.
With ActiveWorkbook.Worksheets("NOS").Sort
.SortFields.Clear
.SortFields.Add Key:=Range("E2"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.SetRange Range("E2:G150")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.Apply
End With
来源:https://stackoverflow.com/questions/54530779/run-time-error-438-in-excel-while-using-sort-function