AppleScript and Numbers – How to Add a Row

applescriptnumbers

This has to be simple: I want to use AppleScript to add a new row at the top of a Numbers sheet called WorkoutSheet in a table called WorkoutDB in a Numbers document call Workout.numbers. (Using Numbers 5.01 on macOS Sierra).

This AppleScript throws the error "Can’t get sheet "WorkoutSheet".

tell application "Numbers"
    activate
    open "/Users/username/Desktop/Workout.numbers"
    delay 2 --- added, but doesn't help
    tell table "WorkoutDB" of sheet "WorkoutSheet"
        add row above first row
    end tell
end tell

Edit: this works; the key was the use of of `document 1' in the tell block:

tell table "WorkoutDB" of sheet "WorkoutSheet" of document 1

And the delay 2 doesn't make a difference; Applescript waits for Numbers to launch and the document to open.


I also added the tell block

tell column "A"
set value of cell 1 to short date string of (current date)
end tell

to add the current date to the first colun of the new row.

tell application "Numbers"
    activate
    open "/Users/markr/Desktop/Workout.numbers"
    tell table "WorkoutDB" of sheet "WorkoutSheet" of document 1
        add row above first row
        tell column "A"
            set value of cell 1 to short date string of (current date)
        end tell
    end tell
end tell

Best Answer

Instead of:

tell table "WorkoutDB" of sheet "WorkoutSheet"  

Use:

tell table "WorkoutDB" of sheet "WorkoutSheet" of document 1

This way Numbers know which document to communicate with.