Henrik Franzén
Henrik Franzén

Reputation: 11

Applescript - Numbers won't close "Untitled"

I'm trying to do an applescript that pastes data into Numbers and then exports it as a csv file.

It's all working fine except that Numbers keeps my previous documents and opens them every time. This resulting in a new "Untitled" every time the script runs, so if the script is run 10 times - Numbers will open the 10 previous documents first. I'm trying quit without saving and close this document without saving without results :(.

How can I make Numbers not open old unsaved files everytime Numbers is started?

on run

set theFilePath to "APPLE SSD SMO128B Media:Users:Henrik:Desktop:my.csv"

tell application "Numbers"
    activate -- If script is run once before the old document that is exported but not saved will open here too
    set thisDocument to make new document
    tell thisDocument
        delete every table of every sheet
    end tell
end tell

tell application "System Events" to keystroke "v" using {option down, shift down, command down}
delay 1
tell application "Numbers"
    export front document as CSV to file theFilePath
    close thisDocument without saving
    delay 1
end tell
tell application "Numbers" to quit without saving

end run

Upvotes: 1

Views: 250

Answers (1)

Ericlm
Ericlm

Reputation: 147

To avoid having Numbers reopening the files you created, you first need to actually save the document to a file, and then ask the Finder to delete it. You can use the following code:

set documentName to "Test"
set targetFolder to path to downloads folder
set myFile to ((targetFolder as string) & documentName & ".numbers")

tell application "Numbers"
    set myDocument to make new document
    
    #Save the file, to delete it just afterward
    save myDocument in file myFile
    
    # Export the document
    set exportFileName to documentName & ".pdf"
    set the targetFilePath to ((targetFolder as string) & exportFileName)
    export myDocument to file targetFilePath as PDF
    
    close
    quit saving no
end tell

tell application "Finder" to delete file myFile

Upvotes: 1

Related Questions