When I use the macro recorder on sorting a ListObject (table), it produces:
ActiveWorkbook.Worksheets("Output").ListObjects("Table4").Sort.SortFields.Add2
which works perfectly fine in my version of Excel. However, this doesn't compile on other Excels. Changing it to .Add
solves the problem.
Google says that .Add2
only exists for ChartObjects - but the recorder records it for a ListObject - and it works here but not in the other Excel (same version).
What is .Add2
? Why does my Excel think that's the correct way?
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 theSortFields
Collection (1), but for serveral other objects (so "only for ChartObject" is not corrrect).Add2
as Function inSortFields
Class; the only difference betweenAdd
andAdd2
seems to be thatAdd2
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 useAdd
unless you need theSubField
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 toAdd
is thatAdd2
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 toAdd
and it will work on older versions of Excel.