Search code examples
performanceemeditor

Optimised Macro to sort Column Order based on Headers


Any thoughts on how to sort very large multi-column data via a macro. So for example, sorting all the columns (or perhaps just the selected adjacent columns?) by A-Z, or 0-9, etc. Similar to the Current single Column sorting options.


Solution

  • Assuming you want to sort all columns by looking at the first row of each column, I wrote a macro:

    function SortOneColumn()
    {
        count = document.GetColumns();
        arr = new Array(count);
        for( i = 0; i < count; ++i ) {
            s = document.GetCell( 1, i + 1, eeCellIncludeNone );
            arr[i] = { name: s, col: i };
        }
        arr.sort( function( a, b ) {
          var nameA = a.name.toLowerCase();
          var nameB = b.name.toLowerCase();
          if( nameA < nameB ) {
            return -1;
          }
          if( nameA > nameB ) {
            return 1;
          }
          return 0;
        });
    
        bSorted = false;
        for( i = 0; i < count; ++i ) {
            if( arr[i].col != i ) {
                document.MoveColumn( arr[i].col + 1, arr[i].col + 1, i + 1 );
                bSorted = true;
                break;
            }
        }
        return bSorted;
    }
    
    while( SortOneColumn() );
    

    There is a potential for optimizing the macro even further, so please let me know if this is not fast enough.

    To run this, save this code as, for instance, SortColumns.jsee, and then select this file from Select... in the Macros menu. Finally, select Run SortColumns.jsee in the Macros menu.