When I use the macro recorder on sorting a ListObject (table), it produces:
ActiveWorkbook.Worksheets(\"Output\").ListObjects(\"Table4\").Sort.SortFields.Add
This is not an answer; I'd like to add what I found out. Should have used comment maybe (but unable to).
Sort.SortFields.Add2
if you define a filter on either a ListObject or a Worksheet.Add2
method is not documented on MSDN for the SortFields
Collection (1), but for serveral other objects (so "only for ChartObject" is not corrrect).Add2
as Function in SortFields
Class; the only difference between Add
and Add2
seems to be that Add2
has one more optional paramter [SubField]
.Conclusion: I guess (but this is only a guess!) that Add2
to is an expansion in functionality that has been implemented with a new name for compatibility reasons. Maybe the macro recorder always uses the most recent function in such a case.
Yor can use Add
unless you need the SubField
parameter.
I still like to get a deeper understanding, like Edwin Ederle asked for. I came across this post because of exact the same situation: using the recorder to learn about coding sort functions, wondering about Add2
, and asking google. This question is (one of) the first google hit(s) if you search for "vba sortfields add2" => maybe worth giving some more information here.
Add2
is a method on SortFields only available in newer versions of Excel. The difference to Add
is that Add2
supports a subfield parameter. For example in a geography field you can sort by population.
The macro recorder uses Add2
to support sorting by subfields. If you don't need to sort by subfields then you can change the recorded code to Add
and it will work on older versions of Excel.