问题
I'm having issues using sort in VBA. I saw this thread for which the answers don't work for me: Sort in VBA
I believe there is a maximum nr of records on which you can sort. Is that correct? I want to sort on 4 criteria in a sheet/table with 188,000 records.
I always get an error on the .Apply
statement: "run-time error '1004': application-defined or object-defined error"
Below my code:
Sub Sort_Table()
Dim sht As Worksheet
Set sht = ActiveWorkbook.Worksheets("Sheet1")
sht.Activate
With sht.ListObjects("Table1").Sort
.SortFields.Clear
.SortFields.Add Key:=Range("Table1[Date]"), SortOn:=xlSortOnValues, Order:=xlAscending ', DataOption:=xlSortNormal
.SortFields.Add Key:=Range("Table1[Country Code]"), SortOn:=xlSortOnValues, Order:=xlAscending ', DataOption:=xlSortNormal
.SortFields.Add Key:=Range("Table1[Rating]"), SortOn:=xlSortOnValues, Order:=xlAscending ', DataOption:=xlSortNormal
.SortFields.Add Key:=Range("Table1[Segment]"), SortOn:=xlSortOnValues, Order:=xlAscending ', DataOption:=xlSortNormal
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
回答1:
Potential problem
Actually maybe you shouldn't the Apply
inside the With
since your object is really updated after the end of the With
block.
For instance here your parameters (.SortFields
etc ...) are not yet set when you use Apply
. I'm not 100% sure because I doesn't have EXCEL to test right now, and it seem not everyone have this problem with this code as you pointed out, but that may be a reason.
(potential) Solution
Try doing:
With sht.ListObjects("Table1").Sort
.SortFields.Clear
.SortFields.Add Key:=Range("Table1[Date]"), SortOn:=xlSortOnValues, Order:=xlAscending ', DataOption:=xlSortNormal
.SortFields.Add Key:=Range("Table1[Country Code]"), SortOn:=xlSortOnValues, Order:=xlAscending ', DataOption:=xlSortNormal
.SortFields.Add Key:=Range("Table1[Rating]"), SortOn:=xlSortOnValues, Order:=xlAscending ', DataOption:=xlSortNormal
.SortFields.Add Key:=Range("Table1[Segment]"), SortOn:=xlSortOnValues, Order:=xlAscending ', DataOption:=xlSortNormal
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
End With
sht.ListObjects("Table1").Sort.Apply
Tell me if this doesn't solve the issue
Other potential problems/solutions
- The sheet you work on (Sorting) is protected
- Check out this question: Excel VBA Sort
Hope it helped anyway ...
来源:https://stackoverflow.com/questions/26037735/excel-vba-sort-error-1004-on-apply