JXA: How to make a range in Numbers

574 Views Asked by At

I tried:

table.selectionRange = table.ranges["C6:C7"];

Gets: Error -1728: Can't get object.

I am able to use the table object: Eg: table.rowCount();

Any ideas?

Note: Syntax 'table.selectionRange = table.ranges["C6:C7"];' was posted as a solution here: How to make a range in Numbers (iWork) using JXA

Added for further clarity:

Logger.logInfo("#Rows " + table.rowCount());
Logger.logInfo("Current Range " + table.selectionRange.name());
Logger.logInfo("#Cols " + table.columnCount());
table.selectionRange = table.ranges["C6:C7"];
Logger.logInfo("New Range " + table.selectionRange.name());

Gives:

/* 2018/02/02 @ 19:36:27.020: Info    : BlockPriceUpdateYPF: #Rows 34 */
/* 2018/02/02 @ 19:36:27.023: Info    : BlockPriceUpdateYPF: Current Range C5:G31 */
/* 2018/02/02 @ 19:36:27.025: Info    : BlockPriceUpdateYPF: #Cols 15 */
Result: Error -1728: Can't get object.
1

There are 1 best solutions below

4
houthakker On

The syntax above is correct, but one needs both:

  1. a valid reference to a currently open table, and
  2. (to set a .selectionRange) GUI focus, obtained, for example, using the .activate() method.
(() => {
    const
        app = Application('Numbers'),
        ws = app.windows,
        w = ws.length > 0 ? (
            ws.at(0)
        ) : undefined,
        sheets = w ? w.document.sheets : [],
        sheet = sheets.length > 0 ? (
            sheets.at(0)
        ) : undefined,
        tables = sheet ? sheet.tables : [],
        table = tables.length > 0 ? (
            tables.at(0)
        ) : undefined;

    app.activate();

    // READ the selection range (name property of table.selectionRange())
    // return table ? (() => {
    //     const maybeSelection = table.selectionRange();
    //     return (typeof maybeSelection) === 'function' ? (
    //         maybeSelection.name()
    //     ) : 'No range selected'
    // })() : 'No active table found in Numbers';

    // or SET the selection:
    return table ? (
        table.selectionRange = table.ranges['D10:D12'],
        'Range now selected: ' + table.selectionRange.name()
    ) : 'No active table';
})();