What is add2 for sortfields

前端 未结 2 533
孤独总比滥情好
孤独总比滥情好 2020-11-30 14:13

When I use the macro recorder on sorting a ListObject (table), it produces:

ActiveWorkbook.Worksheets(\"Output\").ListObjects(\"Table4\").Sort.SortFields.Add         


        
相关标签:
2条回答
  • 2020-11-30 14:54

    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.

    0 讨论(0)
  • 2020-11-30 14:57

    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.

    0 讨论(0)
提交回复
热议问题