macosapplescriptiwork

Duplicate a numbers sheet with applescript


I'm trying to duplicate a sheet in a numbers file (I need a new sheet everyday based on a template) using AppleScript. I'm really new to AppleScript but I'm already using it to fill-in some cells with results I get from a python script I run but this bit is still manual... =/

tell application "Numbers"
tell document 1
    set thisSh to make new sheet with properties {name:"May14"}
    duplicate sheet "Template" to sheet "May14"
end tell
end tell

The code above returns the error: error "Numbers got an error: Sheets can not be copied." number -1717 and, therefore, my question: Is there a way to duplicate a numbers sheet?

I'm currently running iWork '14 with numbers 3.2

Thanks!

P.S. I also tried duplicate every table of sheet "Template" to sheet "May14" with a similar error: Tables can not be copied.


Solution

  • You have two options. You can build the table in the new sheet programmatically, or you can select and copy the table(s) from the first sheet and copy it(them) in the new sheet. Here is code for the second option. Having not seen a screen grab of your template sheet, you may have to adjust, but this should give you everything you need. If you run into complications, please post a screenshot and description of your template sheet. Updated to account for a crazy number of tables in the sheet. Updated again to demonstrate how to change the active sheet.

    tell application "Numbers"
        activate
        tell document 1
            set tempSheet to first sheet whose name is "My Template"
            set active sheet to tempSheet
            tell application "System Events"
                -- deselect all
                keystroke "a" using {command down, shift down}
                delay 0.1
                -- select all containers (tables, text items, etc.)
                keystroke "a" using {command down}
                delay 0.1
                -- copy the containers
                keystroke "c" using {command down}
            end tell
            delay 0.1
            set dateString to (month of (current date)) & (day of (current date)) as string
            set thisSheet to make new sheet with properties {name:dateString}
            tell thisSheet
                delete every table
                tell application "System Events"
                    keystroke "v" using {command down}
                end tell
            end tell
        end tell
    end tell