What is add2 for sortfields

2020-02-06 09:58发布

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?

2条回答
smile是对你的礼貌
2楼-- · 2020-02-06 10:27

This is not an answer; I'd like to add what I found out. Should have used comment maybe (but unable to).

  • I can confirm Excel 365 Business macro recorder records Sort.SortFields.Add2 if you define a filter on either a ListObject or a Worksheet.
  • I can not confirm the macro does not work on same Excel version on another machine (for me it works; tested with Excel 16.0.10228.20080 32Bit).
  • The Add2 method is not documented on MSDN for the SortFields Collection (1), but for serveral other objects (so "only for ChartObject" is not corrrect).
  • The VBA object library (of my Excel version, see above) lists 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.

查看更多
贼婆χ
3楼-- · 2020-02-06 10:40

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.

查看更多
登录 后发表回答