How to set the format of range in Numbers by JXA

How to set the format of range in JXA like the following AppleScript code?


tell application "Numbers"
    activate
    tell document 1
        tell active sheet
            tell table 1
                set the format of range "A2:B2" to currency
            end tell
        end tell
    end tell
end tell

I can't find the documentation related to enumeration in JXA. The format property is enumeration.


table.ranges["A2:B2"].format = "currency";


This code will trigger error (invalid format value).

Replies

Honestly, don’t bother. I spent six weeks reporting JXA defects before it was released and mostly got ignored. It’s simply not fit for purpose.


(I wouldn’t waste time filing bug reports either: once it shipped they pretty much abandoned it, and two years after the PM got fired and the entire department disbanded.)


In this case, the problem is that JavaScript doesn’t have a native Symbol type, so rather than defining one they bridged AE symbol types (class and constant names in AS) to String. That’s usable when performing `get` operations, but falls down on `set` commands because the application has no idea how to coerce the strings that you send it to the symbol types it needs. There are some “compatibility” flags on the Application object that let you fiddle the bridging behavior so that it’ll pack strings as symbols instead, but in practice using those just causes other things to break instead.


My advice: stick to AppleScript for desktop automation. Unlike JXA it has users and documentation to help you when stuck, and while it stinks as a language it’s the only (nominally) supported solution that speaks Apple events right. You can always mix-n-match with other languages by shelling out to `osascript` (for trivial tasks) or calling AppleScript handlers directly via the AppleScript-ObjC bridge. e.g. See: appscript [dot] sourceforge [dot] net/asoc.html


--


p.s. If you’re into JavaScript, then get yourself a copy of Node.js (if you don’t already have it). Wipes the floor with JXA in every way imaginable: tools, libraries, documentation, community, support, etc, etc, etc.


p.p.s. If you’re really curious how a JS-AE bridge should work, `npm install nodeautomation`. I wrote that in a fortnight just to show it can be done right. Unsupported, so tends to break when Apple messes with the OS, but I periodically patch it up. And so it goes.