Scripting in Numbers
Does numbers support scripting?
likewise what level of scripting is available in Keynote pages
If not does anyone think that a lot of the things that people are saying is missing could appear when leopard is launched ( and iwork service update perhaps)
search in here for GUI Scripting. I will try to find the post for you as well and post a link in here. Applescript is not supported, but scripting through menu's is possibly supported. I know Apple has supported Menu type scripting (using the menus to do things), but real scripting is not available.
I am not sure about the level of applescript support in Pages, But am fairly sure they now offer some degree of scripting ability.
Discussions is taking forever today, so I am having a hard time searching for the post i am thinking of.
I think this will work for you I had to leave the forums and do a google on it.
Give it a try and see if it does enough of what your looking for. I don't think so, but its a temporary thing I am hoping.
Jason
Similar Messages
-
How to run scripts in Numbers?
In Yvan Koenig's script, the instructions say
"Save the script as a Script: numberInLetters.scpt
Move the newly created application into the folder:
<startup Volume>:Users:<yourAccount>:Library:Scripts:Applications:Numbers:
Maybe you would have to create the folder Numbers and even the folder Applications by yourself.
Put the cursor in the cell which contains the number to translate.
menu Scripts > Numbers > numberInLetters"
What I have done so far:
placed a script in that location
checked option in AppleScript Editor "Show Script menu in menu bar"
closed and opened Numbers since doing all that
Still no Script menu.
What else do I need to do to get the Script menu to display in Numbers?Hi kharisma,
This is what did with the script:
Selected everything from (* to --[/SCRIPT] (omitting {code} )
Pressed command-C to Copy.
Opened AppleScript Editor.
Went AppleScript Editor > Preferences.
Checked "show Script menu in Menu bar"
Closed preferences.
Clicked in the script area and Pasted.
Went File > Save to open the Save Dialogue.
Chose Script from the File Format: popup menu.
Navigated to the Desktop and clicked Save.
Switched to Finder and opened a Finder window.
Pointed the window to the Desktop. Sorted by Date to bring the newly saved file to the top.
(Later repeated the steps above, saving the same script as an Application with the name Num2wdsResults. Moved both to the folder noted below.)
Clicked otside the window to deslelect it.
Pressed and held the option key.
Went Go > Library to open my user Library.
Released option key.
Navigated/constructed path to Library > Scripts > Applications > Numbers.
Dragged newly saved file to the newly made Numbers folder.
Launched Numbers (which opened a new blank document)
Entered numbers in A2 through A11.
Selected each in turn and went Script menu > Numbers2words
(or on alternate rows, Script menu > num2wds)
Resuts as shown. Note the limitations demonstrated in the yellow rows.
The script may be saved as either a Script or an Application. Both produce the same results.
To run either from within Numbers, select a cell containing a number, then select the script from the Script menu in Numbers.
Regards,
Barry -
Super-scripted Ref Numbers with generated Ref Table (A Glossary?)
Good Morning All!
I have been trying to create a paragraph style that will be applied manually, but when applied Italicizes and adds a sequential super-scripted "reference number". These reference numbers will then be used to produce a table which will sort rows numerically and produce info based on each reference. I will also need this to delete duplicates. I have a remove duplicates script for my ToC and may be able to retrofit it to this, but we'll get to that later. I can single out words with GREP, but without creating my own "parts dictionary" it would be a pain to add a thousand or so part names* to a GREP. I figured the easiest way to do this would be to manually apply a paragraph or character style per instance and then use a script to remove duplicates. If there is a better way to do this I'm open to suggestions.
*Sadly part names aren't always consistent either due to different writers writing styles.
To keep it simple for now I'm wanting it to just produce: Example Row in Table - [Ref # / Blank cell for part number / Part Name (Text that Ref style was applied to) / Blank cell for description]
Example:
I'm running into a problem that my super script numbers wont sit right if its done through a paragraph style as it reads the entire paragraph. I need the style to apply to a word or group of words. I tried creating a numbering system like a ToC, but once again that works off of paragraph styles. I can manually apply a character style but it doesn't have any sequential numbering options. For right now I'm fine manually applying the style for each instance and then copy/pasting part number and description. I'm just looking for something to generate reference numbers and the name that coincides into a row of a target table. In the future it would be amazing to have it access the component dictionary (excell doc) I'm painstakingly building to grab the part number(s) and descriptions so I don't have to copy/paste.
I have been tasked with making multiple writers write the same thing. It feels impossible btw. So I have been creating an indesign template that does a lot of the work for you so that the largest inconsistencies are now handled by Indesign and leave no room for user error. This will not only help my older writers be consistent but will lessen the learning curve on newbies. Let me know if there is something differently I could be doing or if anything has worked well for you. I am open to any and all help/suggestions, I look forward to hearing back!Thanks for the quick response Pete. They would need to be created as well.
I was hoping that they would continue on through pages, but not documents (for booked instances). That they would be numbered on the fly so that if you moved pages around they would renumber themselves and then you could run a script to fix the order in the table. I have the sequential numbering scheme down for automatic figure box numbering. I just cant figure out the in-text mid-paragraph numbering. What do you have for me MVP? -
Hi,
Struggling with Numbers. I believe the solution lies in an applescript. Unfortunately I'm not really familiar with applescript. So, for me, it's like inventing the wheel.
What I would like is this : a table in which I enter a row of data (dates, names, codes, text, etc). Then via a button or (preferably) a code I want this row to be copied, in another (secured) table an additional row opened and to be filled with this data. Would be nice if the data in the first table could be cleared after that. Not essential. Is this possible with applescript? If so, can someone give me something to get me started?
Thanks
MarcelHello
Here's the requested script.
Specify the destination folder's POSIX path in variable dst in _main(). Currently it is set to ~/Desktop/test. Note that ~ (tilde) notation for home directory is NOT supported in AppleScript. The pdf name is obtained from sheet 6's table 1's cell "C5". Note that : (colon) cannot be used in HFS file name and so it is replaced with . (period) here.
Tested with Numbers v2.0.5 under OSX 10.6.8.
Hope this may help,
H
PS. If you're using 10.9, it appears very complicated to enbale GUI scripting for applets or services due to its demanding kindergarten requirements.
cf.
http://macosxautomation.com/mavericks/guiscripting/index.html
_main()
on _main()
set dst to (path to home folder)'s POSIX path & "Desktop/test" -- # POSIX path of destination directory (predefined)
--set dst to (choose folder with prompt "Choose destination folder")'s POSIX path -- # or choose destination directory at run-time
set p2d to (path to desktop)'s POSIX path -- POSIX path of desktop
-- (1) save table as pdf on desktop
tell application "Numbers"
tell document 1
tell sheet 6
tell table 1
--set pdfname to (cell "C5"'s value as Unicode text) & ".pdf" -- [1]
set pdfname to my copy_as_text(cell "C5") & ".pdf" -- to get displayed value; # see [1]
set pdfname to my _gsub(pdfname, ":", ".") -- [2]
my select_table(it)
set pdfname_used to my save_selection_as_pdf(pdfname, {_replace:true})
end tell
end tell
end tell
end tell
-- (2) move saved pdf to destination directory (replacing existing file)
set pdfname_used_posix to _gsub(pdfname_used, "/", ":") -- [3]
do shell script "mv -f " & (p2d & pdfname_used_posix)'s quoted form & " " & dst's quoted form
[1] (cell's value) property can be different than displayed value and there's no (cell's displayed value) property;
thus the only way to get cell's displayed value is to select the cell, perform copy, and get value from clipboard.
[2] : (colon) is reserved in HFS path; here it is replaced with . (period).
[3] / (solidus) is reserved in POSIX path; / in HFS path is to be represented by : (colon) in POSIX path.
end _main
on save_selection_as_pdf(pdfname, {_replace:_replace})
string pdfname : output pdf file name (pdfname = "" denotes default name, e.g., "Untitled.pdf")
boolean _replace : true to replace existing pdfname, false otherwise
return string or boolean : pdf name actually saved in if operation is not canceled, false otherwise
* pdf file is saved in ~/Desktop
* pdf name actually saved in may be different than the given pdfname, e.g., : is replaced with - by Preview.app
* return value is false iff _replace = false and pdfname already exists
script o
property _canceled : false
property _preview_was_running : application "Preview" is running
-- (1) copy current selection
tell application "Numbers"
my _keystroke(it, "c", {command down}, 0.2) -- copy current selection
end tell
-- (2) make new pdf document from clipboard in Preview.app
tell application "Preview"
my _keystroke(it, "n", {command down}, 0.2) -- new pdf document from clipboard
my _keystroke(it, "s", {command down}, 0.2) -- save
end tell
-- (3) save front pdf document in Preview.app
tell application "System Events"
tell process "Preview"
keystroke "d" using {command down} -- desktop
tell (window 1 whose subrole = "AXStandardWindow")
tell sheet 1 -- save sheet
if pdfname ≠ "" then set text field 1's value to pdfname
set pdfname_used to text field 1's value
click button 1 -- Save
delay 0.1
repeat while exists
delay 0.2
tell sheet 1 -- alert sheet (already exists)
if exists then
if _replace then
click button 1 -- Replace
else
click button 2 -- Cancel
set _canceled to true
end if
end if
end tell
if _canceled then click button 2 -- Cancel
end repeat
end tell
end tell
end tell
end tell
-- (4) close or quit Preview.app
tell application "Preview"
if _preview_was_running then
my _keystroke(it, "w", {command down}, 0.2) -- close
else
my _keystroke(it, "q", {command down}, 0.2) -- quit
end if
if _canceled then my _keystroke(it, space, {}, 0.2) -- don't save changes; # see [1]
end tell
-- (5) activate Numbers.app
tell application "Numbers" to activate
if not _canceled then
return pdfname_used
else
return false
end if
end script
tell o to run
[1] this may not work as expected or even fail under 10.7 or later due to its auto-save behaviour.
end save_selection_as_pdf
on copy_as_text(_range)
reference _range : target range
return string : copied value of the range
* this handler destroys the current contents of clipboard
* this handler will change the current selection range to _range
tell application "Numbers"
set _table to (_range as record)'s every reference's item 1
set _sheet to (_table as record)'s every reference's item 1
my select_sheet(_sheet) -- [1]
tell _table
set selection range to _range
end tell
my _keystroke(it, "c", {command down}, 0.2)
end tell
the clipboard as Unicode text
[1] this is required to swtich current sheet
end copy_as_text
on select_table(_table)
reference _table : table object of Numbers
tell application "Numbers"
set _sheet to (_table as record)'s every reference's item 1
my select_sheet(_sheet) -- [1]
tell _table
set selection range to cell 1
end tell
my _keystroke(it, return, {command down, control down}, 0.2)
end tell
[1] this is required to swtich current sheet
end select_table
on select_sheet(_sheet)
reference _sheet : sheet object of Numbers
set _name to _sheet's name
tell application "System Events"
tell process "Numbers"
set frontmost to true
tell (window 1 whose subrole = "AXStandardWindow")
tell splitter group 1
tell splitter group 1
tell scroll area 1
tell outline 1
tell (row 1 whose group 1's static text 1's value = _name)
set selected to true
end tell
end tell
end tell
end tell
end tell
end tell
end tell
end tell
end select_sheet
on _keystroke(_app, _key, _modifiers, _delay)
reference _app : application reference
string _key : character(s) to be keystroked [1]
list _modifiers : list of modifier key to be pressed; enumerations are
command down
option down
shift down
control down
number _delay : post-delay amount [sec]
[1] Character must be present on the current keyboard layout. Otherwise, it is replaced by 'a'.
tell _app to activate
tell application "System Events"
tell (process 1 whose bundle identifier = (_app's id))
keystroke _key using _modifiers
end tell
end tell
if _delay > 0 then delay _delay
end _keystroke
on _gsub(t, s, r)
string t, s, r : source string, search string, replace string
return string : every occurence of s being replaced by r in t
return _join(r, _split(s, t))
end _gsub
on _split(d, t)
string or list d : separator(s)
string t : source string
return list : t splitted by d
local astid0, tt
try
set {astid0, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {} & d}
set tt to t's text items
set AppleScript's text item delimiters to astid0
on error errs number errn
set AppleScript's text item delimiters to astid0
error errs number errn
end try
return tt
end _split
on _join(d, tt)
string d : separator
list tt : source list
return string : tt joined with d
local astid0, t
try
set {astid0, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {} & d}
set t to "" & tt
set AppleScript's text item delimiters to astid0
on error errs number errn
set AppleScript's text item delimiters to astid0
error errs number errn
end try
return t
end _join -
Is there a "remove duplicates" script for Numbers?
Is there an Numbers script that will remove (or flag) duplicates from a list of email addresses?
No bult in script, although there may be one floating around somewhere in cyberspace.
Flagging duplicates is pretty easy, though:
Formula:
B2, and filled down: =COUNTIF(A,A2)
Sort the table (descending) on column B ("Count") to bring all the addresses with duplicates to the top.
Delete the extra copies of each address reporting more than one copy.
Regards,
Barry -
Problem in printing SAP Script Page Numbering
Hi All,
Am facing a problem like : Page Numbering in one of my form is getting printed from 0 (I mean initializing from 0).
Eg : Page 000 of 003
Page 001 of 003
Page 002 of 003
I want to get printed as :
Page 001 of 003
Page 002 of 003
Page 003 of 003
Could you pls help me in this regard.
Thanks In Advance.
Thanks,
Madhu.Hi,
You can solve this problem by setting the page counter mode to "start" and the numbering type as "Arabic", in the page attributes.
Regards,
Ajith V -
Where can I learn Numbers scripting
Hi
I'd love to learn how to script Numbers with AppleScript, but all I managed to find was either general AppleScript tutorials or answers to very specific Numbers problems.
Is there a book or a website where I could learn to script Numbers?
ThanksThere is nothing to my own knowledge.
I will just add that you may go to my iDisk :
<http://public.me.com/koenigyvan>
Navigate to the folder entitled :
For_iWork:iWork '09:for_Numbers09:
You will be able to download a lot of scripts driving Numbers.
Some are old (1st quarter 2009) but youwill be able to extract useful tips and of course, don't forget :
(1) Numbers' Applescript dictionary
(2) http://developer.apple.com/mac/library/documentation/AppleScript/Conceptual/Appl eScriptLangGuide/AppleScriptLanguageGuide.pdf
I work with these two resources, no less, no more.
Yvan KOENIG (VALLAURIS, France) vendredi 6 août 2010 19:43:33 -
How to enter a new Date and Time each day in a Numbers Spreadsheet...
Hi... I have finally decided to move away from Excel and really give Numbers a shot... I have an application where each day I first enter the current date and time into a particular cell of a new row and then I enter some data in cells adjacent (in the same row) as that entered date-time. Then the next day I want to again enter the (new) current date and time and add more data next to that new date-time and so forth day after day... You can't use something as simple as =NOW() because then everyday, ALL of the date-times would change to the current time... Nope, now what I want... I just want to be able to EASILY and QUICKLY enter the current date-time value in one call and then have that specific value stay there forever... In Excel, this is accomplished with the keyboard shortcuts of
<cntl> followed by a semicolon (;) for the date
then enter a single space (for separation of date versus time) followed last by
<command> followed again by a semicolon...
So all together that is,
<cntl><;><sp><command><;>
and that puts something like
4/10/2010 9:49:00 AM
in a single cell...
That's what I now want to be able to do in Numbers...
How do I do that??? Do I use the menubar item "Insert Date and Time" and if so, how exactly do I get the current time to show up in the chosen cell??? With formatting??? Is there a keyboard shortcut method like the one I mentioned that works for Excel?? I've perused the manual and though I found lots on date-time, I didn't see how to do specifically what I want to do... I likely just missed it as surely it must be easy to do...
Any feedback would be much appreciated... thanks... bob...Badunit wrote:
The result of running that script is "UI Enabled = TRUE".
I have cells named by the header values.
This may be the problem.
The script is an old one which deciphered only the letter+digit cell references.
Here is a new version which works with every kind of cell reference.
--[SCRIPT insertDateTime]
Enregistrer le script en tant que Script : insertDateTime.scpt
déplacer l'application créée dans le dossier
<VolumeDeDémarrage>:Users:<votreCompte>:Library:Scripts:Applications:Numbers:
Il vous faudra peut-être créer le dossier Numbers et peut-être même le dossier Applications.
Placez le curseur dans la cellule qui doit recevoir la date_heure
menu Scripts > Numbers > insertDateTime
La cellule pointée reçoit la date_heure.
L'aide du Finder explique:
L'Utilitaire AppleScript permet d'activer le Menu des scripts :
Ouvrez l'Utilitaire AppleScript situé dans le dossier Applications/AppleScript.
Cochez la case "Afficher le menu des scripts dans la barre de menus".
+++++++
Save the script as a Script : insertDateTime.scpt
Move the newly created application into the folder:
<startup Volume>:Users:<yourAccount>:Library:Scripts:Applications:Numbers:
Maybe you would have to create the folder Numbers and even the folder Applications by yourself.
Put the cursor in the cell which must receive the date_time.
menu Scripts > Numbers > insertDateTime
The pointed cell receives the current date_time.
The Finder's Help explains:
To make the Script menu appear:
Open the AppleScript utility located in Applications/AppleScript.
Select the "Show Script Menu in menu bar" checkbox.
Yvan KOENIG (VALLAURIS, France)
2009/03/01
2010/04/11 is now able to treat every kind of cell references
property theApp : "Numbers"
--=====
on run
set {dName, sName, tName, rname, rowNum1, colNum1, rowNum2, colNum2} to my getSelParams()
my doYourDuty(colNum1, rowNum1, tName, sName, dName)
end run
--=====
on doYourDuty(c, r, t, s, d) (*
c = columnIndex
r = rowIndex
t = table's name
s = sheet's name
d = document's name *)
local cdt
set cdt to my cleanThisDate(current date) (* the new date_time as a clean date_time *)
tell application "Numbers" to tell document d to tell sheet s to tell table t
set value of cell r of column c to cdt as text
end tell -- application …
end doYourDuty
--=====
on cleanThisDate(dt)
(* ugly code but once I got date_time with milliseconds so if necessary, I drop them *)
local l
set l to my decoupe(dt as text, ":")
if (count of l) > 3 then set dt to date (my recolle(items 1 thru 3 of l, ":"))
return dt
end cleanThisDate
--=====
on getSelParams()
local r_Name, t_Name, s_Name, d_Name, col_Num1, row_Num1, col_Num2, row_Num2
set {d_Name, s_Name, t_Name, r_Name} to my getSelection()
if r_Name is missing value then
if my parleAnglais() then
error "No selected cells"
else
error "Il n'y a pas de cellule sélectionnée !"
end if
end if
set two_Names to my decoupe(r_Name, ":")
set {row_Num1, col_Num1} to my decipher(item 1 of two_Names, d_Name, s_Name, t_Name)
if item 2 of two_Names = item 1 of two_Names then
set {row_Num2, col_Num2} to {row_Num1, col_Num1}
else
set {row_Num2, col_Num2} to my decipher(item 2 of two_Names, d_Name, s_Name, t_Name)
end if
return {d_Name, s_Name, t_Name, r_Name, row_Num1, col_Num1, row_Num2, col_Num2}
end getSelParams
--=====
set {rowNumber, columnNumber} to my decipher(cellRef,docName,sheetName,tableName)
apply to named row or named column !
on decipher(n, d, s, t)
tell application "Numbers" to tell document d to tell sheet s to tell table t to return {address of row of cell n, address of column of cell n}
end decipher
--=====
set { d_Name, s_Name, t_Name, r_Name} to my getSelection()
on getSelection()
local _, theRange, theTable, theSheet, theDoc, errMsg, errNum
tell application "Numbers" to tell document 1
repeat with i from 1 to the count of sheets
tell sheet i
set x to the count of tables
if x > 0 then
repeat with y from 1 to x
try
(selection range of table y) as text
on error errMsg number errNum
set {_, theRange, _, theTable, _, theSheet, _, theDoc} to my decoupe(errMsg, quote)
return {theDoc, theSheet, theTable, theRange}
end try
end repeat -- y
end if -- x>0
end tell -- sheet
end repeat -- i
end tell -- document
return {missing value, missing value, missing value, missing value}
end getSelection
--=====
on decoupe(t, d)
local l
set AppleScript's text item delimiters to d
set l to text items of t
set AppleScript's text item delimiters to ""
return l
end decoupe
--=====
on parleAnglais()
local z
try
tell application theApp to set z to localized string "Cancel"
on error
set z to "Cancel"
end try
return (z is not "Annuler")
end parleAnglais
--=====
--[/SCRIPT]
It's available on my idisk :
<http://public.me.com/koenigyvan>
Download :
For_iWork:iWork '09:for_Numbers09:insertDateTime.zip
Yvan KOENIG (VALLAURIS, France) dimanche 11 avril 2010 14:16:41 -
In Numbers 08 is it possible to add a link to a file on the local disc within a cell?
In Numbers 08 is it possible to add a link to a file on the local disc within a cell?
As it's a feature asked several times, maybe it will be available in the next version.
I don't know features available in Excel.
Sometimes ago I posted an AppleScript which may perhaps fit your needs.
If you insert in a table pathnames of files stored in your HD, select the cell, trigger the script, open the file.
Here is an updated version :
--[SCRIPT open_a_file]
Enregistrer le script en tant que Script : open_a_file.scpt
déplacer le fichier ainsi créé dans le dossier
<VolumeDeDémarrage>:Utilisateurs:<votreCompte>:Library:Scripts:Applications:Numb ers:
Il vous faudra peut-être créer le dossier Numbers et peut-être même le dossier Applications.
Sélectionner la cellule contenant le chemin d'accès
Aller au menu Scripts , choisir Numbers puis choisir “open_a_file”
ouvre le fichier.
--=====
L'aide du Finder explique:
L'Utilitaire AppleScript permet d'activer le Menu des scripts :
Ouvrez l'Utilitaire AppleScript situé dans le dossier Applications/AppleScript.
Cochez la case "Afficher le menu des scripts dans la barre de menus".
--=====
Save the script as a Script: open_a_file.scpt
Move the newly created file into the folder:
<startup Volume>:Users:<yourAccount>:Library:Scripts:Applications:Numbers:
Maybe you would have to create the folder Numbers and even the folder Applications by yourself.
Select the cell containing the pathname
Go to the Scripts Menu, choose Numbers, then choose “open_a_file”
open the file
--=====
The Finder's Help explains:
To make the Script menu appear:
Open the AppleScript utility located in Applications/AppleScript.
Select the "Show Script Menu in menu bar" checkbox.
Save this script as a … Script in the "Folder Actions Scripts" folder
<startupVolume>:Library:Scripts:Folder Action Scripts:
--=====
Yvan KOENIG (VALLAURIS, France)
2010/02/02
2011/04/28 - replaced the getSelParams handler by the get_SelParams one
--=====
on run
set {dName, sName, tName, rowNum1, colNum1, rowNum2, colNum2} to my get_SelParams()
tell application "Numbers" to tell document dName to tell sheet sName to tell table tName
set maybe to value of cell rowNum1 of column colNum1
end tell -- Numbers
tell application "Finder" to open maybe
end run
--=====
set { dName, sName, tName, rowNum1, colNum1, rowNum2, colNum2} to my get_SelParams()
on get_SelParams()
local d_Name, s_Name, t_Name, row_Num1, col_Num1, row_Num2, col_Num2
tell application "Numbers" to tell document 1
set d_Name to its name
set s_Name to ""
repeat with i from 1 to the count of sheets
tell sheet i to set maybe to the count of (tables whose selection range is not missing value)
if maybe is not 0 then
set s_Name to name of sheet i
exit repeat
end if -- maybe is not 0
end repeat
if s_Name is "" then
if my parleAnglais() then
error "No sheet has a selected table embedding at least one selected cell !"
else
error "Aucune feuille ne contient une table ayant au moins une cellule sélectionnée !"
end if
end if
tell sheet s_Name to tell (first table where selection range is not missing value)
tell selection range
set {top_left, bottom_right} to {name of first cell, name of last cell}
end tell
set t_Name to its name
tell cell top_left to set {row_Num1, col_Num1} to {address of its row, address of its column}
if top_left is bottom_right then
set {row_Num2, col_Num2} to {row_Num1, col_Num1}
else
tell cell bottom_right to set {row_Num2, col_Num2} to {address of its row, address of its column}
end if
end tell -- sheet…
return {d_Name, s_Name, t_Name, row_Num1, col_Num1, row_Num2, col_Num2}
end tell -- Numbers
end get_SelParams
--=====
on decoupe(t, d)
local l
set AppleScript's text item delimiters to d
set l to text items of t
set AppleScript's text item delimiters to ""
return l
end decoupe
--=====
on parleAnglais()
local z
try
tell application "Numbers" to set z to localized string "Cancel"
on error
set z to "Cancel"
end try
return (z is not "Annuler")
end parleAnglais
--=====
--[/SCRIPT]
Oops, I forgot that you are asking about Numbers '08 which hasn't AppleScript support.
Yvan KOENIG (VALLAURIS, France) jeudi 28 avril 2011 16:26:39
Please :
Search for questions similar to your own before submitting them to the community -
Use of applescript in numbers to automatically analyze data?
Hi all,
I am trying to figure out if it is possible to use applescript and numbers to achieve the following:
(1) Import a CSV file
(2) Work out an average and standard deviation for particular columns of data in that CSV file
(3) Copy and paste out those averages and standard deviations to a separate numbers file, along with the name of the original data file, so in the end I have a file that contains a number of rows, each one containing the results for each data file and the file name.
The files (from an analytical instrument) are all the same, so ideally I could use automator and/or applescript to automatically run through a directory of csv files to achieve this.
I know only a small amount of very basic programming. I don't want someone to write this for me, but if someone could offer some pointers or examples that would be very helpful. Or tell me that what I am trying to do is foolish, and use something else instead.
ThanksAs I got a sample file, I was able to build a script matching the full requirements.
Here is a revised version which may be useful for other users.
--[SCRIPT average&stdev_CSV]
Enregistrer le script en tant que Script : average&stdev_CSV.scpt
déplacer le fichier ainsi créé dans le dossier
<VolumeDeDémarrage>:Users:<votreCompte>:Library:Scripts:Applications:Numbers:
Il vous faudra peut-être créer le dossier Numbers et peut-être même le dossier Applications.
aller au menu Scripts , choisir Numbers puis choisir average&stdev_CSV
Sélectionner un dossier contenant des fichiers CSV.
Le script ouvre ces fichiers dans Numbers,
calcule les valeurs MOYENNE() et ECARTYPE()
écrit celles-ci avec le nom du document dans un fichier texte.
Après traitement de tous les fichiers le fichier texte et ouvert dans Numbers.
On peut également enregistrer le script en tant que progicile (application sou 10.6.x).
Il suffira alors de glisser/déposer l'icone du dossier à traiter sur celle du script_application.
--=====
L'aide du Finder explique:
L'Utilitaire AppleScript permet d'activer le Menu des scripts :
Ouvrez l'Utilitaire AppleScript situé dans le dossier Applications/AppleScript.
Cochez la case "Afficher le menu des scripts dans la barre de menus".
--=====
Save the script as a Script: average&stdev_CSV.scpt
Move the newly created file into the folder:
<startup Volume>:Users:<yourAccount>:Library:Scripts:Applications:Numbers:
Maybe you would have to create the folder Numbers and even the folder Applications by yourself.
go to the Scripts Menu, choose Numbers, then choose "average&stdev_CSV"
Select a folder containing CSV files.
The script open them in Numbers,
calculate the AVERAGE() and STDEV() values
write them with the file name in a text file.
When all files are treated, the text file is opened in Numbers.
You may also save the script as an application package (application under 10.6.x).
Then drag & drop the icon of the folder to treat on the scipt_application icon.
--=====
The Finder's Help explains:
To make the Script menu appear:
Open the AppleScript utility located in Applications/AppleScript.
Select the "Show Script Menu in menu bar" checkbox.
--=====
Yvan KOENIG (VALLAURIS, France)
2010/06/10
2010/06/11 -- now read the csv file only once
--=====
property permis : {"public.comma-separated-values-text", "public.csv"}
property AVERAGE_loc : missing value
property STDEV_loc : missing value
property delim : missing value
property deci : missing value
property altDelim : missing value
property altDeci : missing value
property dossier_temporaire : missing value
property mon_Rapport : missing value
--=====
Entry point used when we double click the script's icon
or when we call it from the Scripts menu .
on run
if my parleAnglais() then
set le_prompt to "Choose a folder containing CSV file …"
else
set le_prompt to "Choisir un dossier contenant des fichiers CSV …"
end if -- parleAnglais
my main(choose folder with prompt le_prompt without invisibles)
end run
--=====
Entry point used when we drag & drop a folder icon on the application_script's icon
on open sel
my main(sel)
end open
--=====
on main(selected_item) -- it's an alias
local isFolder, nomdurapport, les_fichiers, type_ID, un_fichier, nombrededocuments, nomdutableur
the selected folder's pathname
set selected_item to selected_item as text
tell application "System Events"
set isFolder to class of disk item selected_item is folder
end tell -- System Events
if not isFolder then
if my parleAnglais() then
error "You must select a folder containing CSV file …"
else
error "Vous devez choisir un dossier contenant des fichiers CSV …"
end if -- parleAnglais
end if -- not isFolder
Init once variables which will be used later.
set dossier_temporaire to (path to temporary items) as text (* property *)
set AVERAGE_loc to my getLocalizedFunctionName("Numbers", "AVERAGE") & "(" (* property *)
set STDEV_loc to my getLocalizedFunctionName("Numbers", "STDEV") & "(" (* property *)
set {delim, deci, altDelim, altDeci} to my getLocalized_Delimiters() (* properties *)
set nomdurapport to "resume" & my dateTimeStamp() & ".txt" (* locale *)
set mon_Rapport to dossier_temporaire & nomdurapport (* property *)
Extract the list of items stored in the selected folder.
Create the resumeyyyymmddhhmmss.txt temporary file.
tell application "System Events"
set les_fichiers to every disk item of folder selected_item
make new file at end of folder dossier_temporaire with properties {name:nomdurapport}
end tell
Scan the items stored in the folder.
Skip the folders and documents which aren't csv ones.
repeat with un_fichier in les_fichiers
tell application "System Events"
if class of un_fichier is folder then
set type_ID to "Oops, I‘m a folder" (* so it will not be deciphered *)
else
set type_ID to type identifier of un_fichier
set un_fichier to path of un_fichier
end if
end tell -- System Events
if type_ID is in my permis then my traiteun_fichier(unfichier)
end repeat -- with un_fichier
The scan is done, open the resumeyyyymmddhhmmss.txt temporary file in Numbers.
tell application "Numbers"
set nombrededocuments to count of documents
open mon_Rapport
repeat while (count of documents) = nombrededocuments
delay 0.2
end repeat
set nomdutableur to name of document 1
Set cells format to the Scientific one but I can't define the number of decimals !
tell document 1 to tell sheet 1 to tell table 1
set format of range ("B1 : " & name of last cell) to scientific
end tell
save document 1 in (selected_item & nomdutableur)
end tell -- Numbers
Delete the temporary text file
tell application "System Events" to delete disk item mon_Rapport
Reset properties so there content will not be stored in the script
set AVERAGE_loc to missing value
set STDEV_loc to missing value
set delim to missing value
set altDelim to missing value
set deci to missing value
set altDeci to missing value
set dossier_temporaire to missing value
set mon_Rapport to missing value
end main
--=====
on traiteunfichier(unFichier) (* text item *)
local dossierdetravail, nomdu_csvtemporaire, csv_temporaire, utile, cnt, part2
local |dernière|, nombreDeDocuments, nomdutableur, laPlage
tell application "System Events"
tell disk item unFichier
set dossierdetravail to path of container -- of disk item unFichier
set nomdu_csvtemporaire to name -- of disk item unFichier
end tell -- unFichier
if nomdu_csvtemporaire does not end with ".csv" then set nomdu_csvtemporaire to nomdu_csvtemporaire & ".csv"
set csv_temporaire to (dossier_temporaire & nomdu_csvtemporaire)
if exists disk item csv_temporaire then delete disk item csv_temporaire
make new file at end of folder dossier_temporaire with properties {name:nomdu_csvtemporaire}
end tell -- System Events
Read the entire file
set utile to (read file unFichier)
Check that it's matching our requirements. I'm not sure that the second test is always valid.
if (utile contains "#=-=-=-=-=-=-=-=-=") and utile contains "#=-=-=-=-=-=-=-=-=End ./conf/ccia" then
set cnt to offset of "#=-=-=-=-=-=-=-=-=" in utile
Extract the second part which isn't formatted as the first one.
set part2 to text cnt thru -1 of utile
Extract the first part to decipher it.
set utile to (text 1 thru (cnt - 1) of utile) as text
Grabs the index of lower row
set |dernière| to count of (paragraphs of utile)
An ultimate test to be sure that the file is for us.
if (|dernière| > 0) and text -13 thru -2 of (paragraph 6 of utile) is "NFitsAvg'd" then
Normalize the datas according to the local settings
if not ((utile contains delim) and utile contains deci) then
if utile contains altDelim then set utile to my remplace(utile, altDelim, delim)
if utile contains altDeci then set utile to my remplace(utile, altDeci, deci)
end if
Write the normalized beginning and the untouched part2 in a temporary csv file.
write utile to file csv_temporaire
write part2 to file csv_temporaire starting at eof
Open the temporary csv in Numbers
tell application "Numbers"
set nombreDeDocuments to count of documents
open csv_temporaire
repeat while (count of documents) = nombreDeDocuments
delay 0.2
end repeat
set nomdutableur to name of document 1
tell document 1 to tell sheet 1 to tell table 1
Insert a row at top to insert the required formulas.
add row above first row
Insert the formulas calculating the AVERAGEs and the STDEVs .
repeat with c from 2 to 16 by 2
set laPlage to (name of cell 8 of column c) & " : " & name of cell |dernière| of column c
set value of cell 1 of column c to "=" & AVERAGE_loc & laPlage & ")"
set value of cell 1 of column (c + 1) to "=" & STDEV_loc & laPlage & ")"
end repeat -- with c
Extract the calculated values to build a new row in the resume.
set une_ligne to {nomdu_csvtemporaire}
tell row 1
repeat with c from 2 to 17
copy (value of cell c) as text to end of une_ligne
--copy (value of cell c) to end of une_ligne
end repeat
end tell -- row 1
end tell -- document
Save the new Numbers document.
I don't know if it is useful but it's easy to remove or disable the instruction.
save document 1 in (dossierdetravail & nomdutableur)
close document 1 saving no (* So, if you disable the Save instruction, it will close quietly *)
end tell -- Numbers
Write the new row in the resume text file.
write (my recolle(une_ligne, tab) & return) to file mon_Rapport starting at eof
end if -- (|dernière| > 0) or
end if -- read file unFichier…
Delete the temporary csv file
tell application "System Events" to delete file csv_temporaire
end traiteunfichier
--=====
Creates a new iWork document from the Blank template and returns its name.
example:
set myNewDoc to my makeAnIworkDoc(theApp)
on makeAnIworkDoc(theApp)
local t, n
if theApp is "Pages" then
set commun to "iWork '" & my get_iWorkNum("Pages") & ":Pages.app:Contents:Resources:Templates:Blank.template:"
try
set t to ((path to applications folder as text) & commun) as alias
on error
set t to ("Western 2:Applications communes:iWork '" & commun) as alias
end try
else if theApp is "Numbers" then
set commun to "iWork '" & my get_iWorkNum("Numbers") & ":Numbers.app:Contents:Resources:Templates:Blank.nmbtemplate:"
try
set t to ((path to applications folder as text) & commun) as alias
on error
set t to ("Western 2:Applications communes:" & commun) as alias
end try
else
if my parleAnglais(theApp) then
error "The application “" & a & "“ is not accepted !"
else
error "l’application « " & a & " » n’est pas gérée !"
end if
end if
tell application theApp
set n to count of documents
open t
repeat until (count of documents) > n
delay 0.1
end repeat
set n to name of document 1
end tell -- theApp
return n
end makeAnIworkDoc
--=====
on dateTimeStamp()
return (do shell script "date +_%Y%m%d-%H%M%S")
end dateTimeStamp
--=====
Set the parameter delimiters which must be used in Numbers formulas
on getLocalized_Delimiters()
if character 2 of (0.5 as text) is "." then
return {",", ".", ";", ","}
else
return {";", ",", ",", "."}
end if
end getLocalized_Delimiters
--=====
on get_iWorkNum(a)
local verNum
tell application a to set verNum to item 1 of my decoupe(get version, ".")
if (a is "Numbers" and verNum is "2") or (a is "Pages" and verNum is "4") then
return "09"
else
return "11"
end if
end get_iWorkNum
--=====
Useful to get function's localized name if we need to build formulas
examples:
set OFFSET_loc to my getLocalizedFunctionName("Numbers", "OFFSET")
set ADDRESS_loc to my getLocalizedFunctionName(theApp, "ADDRESS")
set INDIRECT_loc to my getLocalizedFunctionName(theApp, "INDIRECT")
on getLocalizedFunctionName(theApp, x)
return my getLocalizedName(theApp, x, (path to application support as text) & "iWork '" & ¬
my get_iWorkNum(theApp) & ":Frameworks:SFTabular.framework:Versions:A:Resources:")
end getLocalizedFunctionName
--=====
on getLocalizedName(a, x, f)
tell application a to return localized string x from table "Localizable" in bundle file f
end getLocalizedName
--=====
on parleAnglais()
local z
try
tell application "Numbers" to set z to localized string "Cancel"
on error
set z to "Cancel"
end try
return (z is not "Annuler")
end parleAnglais
--=====
on decoupe(t, d)
local TIDs, l
set TIDs to AppleScript's text item delimiters
set AppleScript's text item delimiters to d
set l to text items of t
set AppleScript's text item delimiters to TIDs
return l
end decoupe
--=====
on recolle(l, d)
local TIDs, t
set TIDs to AppleScript's text item delimiters
set AppleScript's text item delimiters to d
set t to l as text
set AppleScript's text item delimiters to TIDs
return t
end recolle
--=====
replaces every occurences of d1 by d2 in the text t
on remplace(t, d1, d2)
local TIDs, l
set TIDs to AppleScript's text item delimiters
set AppleScript's text item delimiters to d1
set l to text items of t
set AppleScript's text item delimiters to d2
set t to l as text
set AppleScript's text item delimiters to TIDs
return t
end remplace
--=====
--[/SCRIPT]
Yvan KOENIG (VALLAURIS, France) vendredi 11 juin 2010 19:01:46 -
Save as- for Dummies (Numbers version)
Here is a clean way to retrieve Save As… in Numbers.
--(SCRIPT Numbers_save_a_copy]
Enregistrer le script en tant que Script : Numbers_save_a_copy.scpt
déplacer le fichier créé dans le dossier
<VolumeDeDémarrage>:Utilisateurs:<votreCompte>:Bibliothèque:Scripts:Applications :Numbers:
Il vous faudra peut-être créer le dossier Numbers et peut-être même le dossier Applications.
Aller au menu Scripts , choisir Numbers puis choisir “Numbers_save_a_copy”
Le script enregistre une copie du document au premier plan
au format natif de Numbers en ajoutant la date et l'heure au nom du fichier.
--=====
L'aide du Finder explique:
L'Utilitaire AppleScript permet d'activer le Menu des scripts :
Ouvrez l'Utilitaire AppleScript situé dans le dossier Applications/AppleScript.
Cochez la case "Afficher le menu des scripts dans la barre de menus".
+++++++++
Save the script as a Script: Numbers_save_a_copy.scpt
Move the newly created file into the folder:
<startup Volume>:Users:<yourAccount>:Library:Scripts:Applications:Numbers:
Maybe you would have to create the folder Numbers and even the folder Applications by yourself.
Go to the Scripts Menu, choose Numbers, then choose “Numbers_save_a_copy”
The script saves the frontmost document
in the native Numbers format in a date_time stamped file.
--=====
The Finder's Help explains:
To make the Script menu appear:
Open the AppleScript utility located in Applications/AppleScript.
Select the "Show Script Menu in menu bar" checkbox
--=====
Yvan KOENIG (VALLAURIS, France)
2011/08/12
on run
local docPath, docName, docFolder, fileName, theExt, newName, newPath
set major_OS to get system attribute "sysv"
Grab infos about the open doc at front *)
tell application "Numbers"
tell document 1
set docPath to its path
set docName to its name
end tell
if major_OS ≥ 4208 then save docName (* Required for Lion *)
end tell
Grab infos about the file from which the doc was open *)
tell application "System Events" to tell disk item docPath
set docFolder to path of container
set fileName to name
set theExt to name extension
end tell
Build an unique name for the new document *)
if theExt is not "" then
set newName to (text 1 thru -(2 + (length of theExt)) of fileName) & (do shell script "date +_%Y%m%d_%H%M%S.") & theExt
else
set newName to fileName & (do shell script "date +_%Y%m%d_%H%M%S")
end if
Create the new file *)
tell application "System Events"
make new file at end of folder docFolder with properties {name:newName}
end tell
set newPath to (docFolder & newName) as alias
Save a copy in the newly created file *)
tell application "Numbers"
save document docName in newPath
end tell
end run
--=====
--[/SCRIPT]
--{code}
Yvan KOENIG (VALLAURIS, France) vendredi 19 août 2011 22:18:22
iMac 21”5, i7, 2.8 GHz, 4 Gbytes, 1 Tbytes, mac OS X 10.6.8 and 10.7.0
My iDisk is : <http://public.me.com/koenigyvan>Here is an other one.
Read carefully the explanations given at the very beginning, in French then in English.
With this one you master the time when you save. CAUTION, Autosave is unable to do it's duty when you work on a document open with the script so don't forget to ask the script to save from time to time.
With this dedicated to Numbers script, the most interesting piece of code is the one used to grab the status of the document when we open it to be able to reset it after inserting the items storing the path to folder to save in and the doc shortname.
--(SCRIPT Numbers_without_autosave]
Enregistrer le script en tant qu'application sur le Bureau.
Glisser une icône de document Numbers sur l'icône de l’application
ouvre le document, le duplique, ferme l'original renomme la copie en ajoutant l'information date_heure
crée une table dans une feuille afin d'y stocker le chemin d'accès au dossier source et le nom court du document original.
Travailler sur le document et de temps à autres, cliquer sur l'cône du script application afin d'enregistrer
le document et repartir avec une copie qui n'ayant jamais été enregistré ne sera pas autoenregistré.
Bien entendu, quand vous aurez fini de travailler sur le document il vous faudra l'enregistrer comme autrefois.
--=====
L'aide du Finder explique:
L'Utilitaire AppleScript permet d'activer le Menu des scripts :
Ouvrez l'Utilitaire AppleScript situé dans le dossier Applications/AppleScript.
Cochez la case "Afficher le menu des scripts dans la barre de menus".
+++++++++
Save the script as an application on the Desktop.
Drop a Numbers doc icon on the application's one, open the document, duplicate it, save the original if it was created from a template,
rename the duplicate inserting a date_time stamp, create a table in a sheet to store the pathname to the source folder and the short name of the original.
After that you may work upon the document. From time to time, click the script's icon to save the document and replace it by a fresh replicate. So this one which was never saved will not be autosaved.
When you have finished to work upon the doc, save it as you did in the past.
--=====
The Finder's Help explains:
To make the Script menu appear:
Open the AppleScript utility located in Applications/AppleScript.
Select the "Show Script Menu in menu bar" checkbox
--=====
Yvan KOENIG (VALLAURIS, France)
2011/08/22
property permitted : {"com.apple.iWork.Numbers.numbers", "com.apple.iWork.Numbers.sffnumbers"}
property modeles : {"com.apple.iWork.Numbers.template", "com.apple.iWork.Numbers.sfftemplate"}
property boxName : "pathname_shortname_emantrohs_emanhtap"
--=====
on run
local docName, path_infos, docFolder, nomCourt, docPath, nbd
my controle_versions()
Grab infos about the frontmost Numbers document *)
tell application "Numbers"
set docName to name of document 1
tell document docName
Try to extract the infos stored by the open handler *)
try
tell sheet boxName to tell table boxName
set docFolder to value of cell "A1"
set nomCourt to value of cell "B1"
end tell
on error
if my parleAnglais() then
error "The document “" & docName & "”" & return & "wasn’t open with this script !"
else
error "Le document « " & docName & " »" & return & "n’a pas été ouvert avec ce script !"
end if
end try
end tell -- document
end tell -- Numbers
set docPath to docFolder & docName
tell application "System Events"
This test was useful during my tests, now it's useless *)
if not (exists disk item docPath) then
make new file at end of folder docFolder with properties {name:docName}
end if
end tell -- System Events
set docPath to docPath as alias
I don't understand why I must apply save - close - open but without that it fails *)
tell application "Numbers"
save document docName in docPath
close document docName
open docPath
set nbd to count of documents
end tell
my selectMenu("Numbers", 3, 9) (* Duplicate ( 9 in Numbers, 10 in Pages )*)
Wait the availability of the duplicate *)
tell application "Numbers"
repeat 100 times
if (get count of documents) > nbd then exit repeat
delay 0.2
end repeat
Now we may close the 'old' document *)
close document docName without saving
end tell -- Numbers
Build a date_time stamped name for next version *)
set docName to nomCourt & my build_a_stamp() & ".numbers"
tell application "Numbers"
set name of document 1 to docName
end tell
end run
--=====
on open (sel)
local docPath, docFolder, fileName, theExt, typeID, nomCourt, nouveauNomCourt, newPath, oldUnits, docName, nbd
Apply consistency checks *)
my controle_versions()
set docPath to sel's item 1 (* Here, docPath is an alias *)
Extract some infos about the original document *)
tell application "System Events" to tell disk item (docPath as text)
set docFolder to path of container
set fileName to name
The try block may be useful if an user is fool enough to drag & drop a folder on the scrip’s icon *)
try
set theExt to name extension
on error
set theExt to ""
end try
try
set typeID to type identifier
on error
set typeID to ""
end try
end tell
Check that the dragged item is a Numbers document *)
if (typeID is not in permitted) and (typeID is not in modeles) then error number -128
Strip the name extension if there is one *)
if theExt is not "" then
set nomCourt to (text 1 thru -(2 + (length of theExt)) of fileName)
else
set nomCourt to fileName
end if
If the original is a template, we will save the newly created file *)
if typeID is in modeles then
set nouveauNomCourt to nomCourt & my build_a_stamp()
set fileName to nouveauNomCourt & ".numbers"
Create a new file *)
tell application "System Events"
make new file at end of folder docFolder with properties {name:fileName}
end tell
set newPath to (docFolder & fileName) as alias
end if
tell application "Numbers"
open docPath
if typeID is in modeles then
Original is a template so save the new doc once *)
save document 1 in newPath
set name of document 1 to fileName
end if
set docName to name of document 1
set nbd to count of documents
end tell
my selectMenu("Numbers", 3, 9) (* Duplicate ( 9 in Numbers, 10 in Pages )*)
Wait the availability of the duplicate *)
tell application "Numbers"
repeat 100 times
if (get count of documents) > nbd then exit repeat
delay 0.2
end repeat
Now may close the 'original' document *)
close document docName without saving
end tell
set docName to nomCourt & my build_a_stamp() & ".numbers"
tell application "Numbers"
set name of document 1 to docName
set {dName, sName, tName, rowNum1, colNum1, rowNum2, colNum2} to my get_SelParams()
tell document docName
make new sheet with properties {name:boxName}
tell sheet boxName
delete table 1
make new table with properties {name:boxName, row count:2, column count:3}
tell table boxName
remove column 1
remove row 1
set value of cell "A1" to docFolder
set value of cell "B1" to nomCourt
end tell -- table
end tell -- sheet
Reset the entry settings *)
if tName is "" then
my selectSheet(dName, sName)
else
my selectTable(dName, sName, tName)
if rowNum1 > 0 then
tell sheet sName to tell table tName
set selection range to range (name of cell rowNum1 of column colNum1 & ":" & name of cell rowNum2 of column colNum2)
end tell
end if
end if
end tell -- document
end tell -- Numbers
end open
--=====
on build_a_stamp()
return do shell script "date +_%Y%m%d_%H%M%S"
end build_a_stamp
--=====
on controle_versions()
local app_Version, sysv
tell application "Numbers" to set app_Version to version
set sysv to system attribute "sysv"
if (app_Version < "2.1") or (sysv < 4208) then error number -128
end controle_versions
--=====
set { dName, sName, tName, rowNum1, colNum1, rowNum2, colNum2} to my get_SelParams()
tell application "Numbers" to tell document dName to tell sheet sName to tell table tName
Enhanced version returning the name of the selected sheet or the name of the selected table if no cell is selected *)
on get_SelParams()
script myScript
property liste_feuilles : {}
local d_name, s_name, t_name, row_num1, col_num1, row_num2, col_num2
local sheet_size, i, r, s, t_index, sheet_row
tell application "Numbers" to tell document 1
set d_name to its name
set s_name to ""
repeat with i from 1 to the count of sheets
tell sheet i to set maybe to the count of (tables whose selection range is not missing value)
if maybe is not 0 then
set s_name to name of sheet i
exit repeat
end if -- maybe is not 0
end repeat
end tell -- Numbers…
if s_name > "" then
tell application "Numbers" to tell document d_name to tell sheet s_name to tell (first table where selection range is not missing value)
tell selection range to set {top_left, bottom_right} to {name of first cell, name of last cell}
set t_name to its name
tell cell top_left to set {row_num1, col_num1} to {address of its row, address of its column}
if top_left is bottom_right then
set {row_num2, col_num2} to {row_num1, col_num1}
else
tell cell -
Updated Table Name Changes Applescript Operation in Numbers 3.5
I've been using Applescript in Numbers for some time to copy/paste data (set cell values) from one sheet table to another sheet table.
My original script was heavily cribbed from something Yvan Koenig had posted 2-3 years ago.
I recently updated to Yosemite and Numbers 3.5 after testing to ensure my original script remained functional (and it did).
I subsequently updated my source data table by duplicating my old table and editing this new source.
I then updated my Applescript to to reference the new source table.
Testing yielded a good functional result, but Numbers changed its behavior by displaying its work while setting values in the target sheet table.
This obviously slows the script down and adds measurable processing time given the amount of data being moved.
Does anyone know how I can prevent this behavior from occurring?
I don't believe I changed anything material in my original script so I'm really not sure why Numbers changed its behavior.
I have included my script below. Thanks very much for any help!
property the_goods : {}
property patient_name : {}
property patient_count : {}
property run_date : {}
on run
set sheet_source to "1500 EXPORT"
set table_source to "OA Data"
set column_source to 1
set row_source to 2
set sheet_destination to "CLEARING HOUSE EXPORT"
set table_destination to "Export Table"
set column_destination to 1
set nb_rows to 0
set nb_columns to 244
set patient_sheet to "SESSION DB"
set patient_source to "User Input Table"
set patient_tracker to "Tracking Table"
set source_column to 3
set source_row to 2
set destination_column to 2
set date_column to 3
set patient_count_column to 3
set patient_count_row to 3
set run_date_row to 5
tell application "Numbers"
set document_source to name of front document as string
set document_destination to name of front document as string
end tell
tell application "Numbers"
tell document document_source to tell sheet patient_sheet to tell table patient_source
set patient_count to value of cell patient_count_column of row patient_count_row
set run_date to value of cell patient_count_column of row run_date_row
end tell
end tell
set row_destination to patient_count
tell application "Numbers"
tell document document_source to tell sheet sheet_source to tell table table_source
set the_goods to value of cells column_source thru (column_source + nb_columns) of rows row_source thru (row_source + nb_rows)
end tell
tell document document_destination to tell sheet sheet_destination to tell table table_destination
set r to 0
repeat with one_row in the_goods
tell row (row_destination + r)
set c to 0
repeat with one_value in one_row
set value of cell (column_destination + c - 0) to one_value
set c to c + 1
end repeat
end tell
set r to r + 1
end repeat
end tell
tell document document_destination to tell sheet patient_sheet to tell table patient_source
activate
end tell
tell document document_destination to tell sheet patient_sheet to tell table patient_source
set patient_name to value of cell source_column of row source_row
end tell
tell document document_destination to tell sheet patient_sheet to tell table patient_tracker
set value of cell destination_column of row row_destination to patient_name
set value of cell date_column of row row_destination to run_date
end tell
end tell
set the_goods to {}
set patient_name to {}
set patient_count to {}
set run_date to {}
end runHere is a simple example that copies values from a source row 3 in Table 1 to a target row 5 in Table 2.
On my aging MBA it was very fast (about a second) with 150 columns.
In addition to speed, an advantage of this approach is that you don't have to code table dimensions; the target table will expand automatically if needed.
Save the script in a script folder (in my case ~/Library/Scripts/Applications/Numbers) and run it from there by choosing it from the script menu. (Running it from Script Editor will paste the values into Script Editor instead of into Numbers as you want).
If keeping the original number format is important, substitute 'formatted value' for 'value' in the script.
SG
property src : {d:1, s:"Sheet 1", t:"Table 1", r:3}
property tgt : {d:1, s:1, t:"Table 2", r:5}
tell application "Numbers"
tell document (src's d)
tell sheet (src's s)
tell table (src's t)
tell row (src's r)
set vv to cells's value -- makes AppleScript list
set the clipboard to my makeTSV(vv)
end tell
end tell
end tell
end tell
tell document (tgt's d)
tell sheet (tgt's s)
tell table (tgt's t)
set the selection range to row (tgt's r)'s cell 1
tell application "Numbers" to activate
tell application "System Events" to keystroke "v" using {option down, shift down, command down}
end tell
end tell
end tell
end tell
to makeTSV(aLst) -- turns AppleScript list into tab-delimited string
set oTID to AppleScript's text item delimiters
set AppleScript's text item delimiters to tab
set tsvStr to aLst as text
set AppleScript's text item delimiters to oTID
return tsvStr
end makeTSV -
How to display the current day value in Numbers app?
In Numbers 3.2.2, where the current date and time happens to be 17 Dec. 2014 11:46am:
What formula will display the current date's numeral value?
What formula will display the current month's short name as text?
What formula will display the current year in four digits?
What formula will display the current time in the style "11:46am"?
Appreciated.I've taken the liberty of tweaking that handy script to format the date as requested by the OP:
on run {}
set right_now to (current date)
set short_month to text 1 thru 3 of (month of right_now as string)
set the_year to year of right_now as string
set the_day to day of right_now as string
set short_time to text 1 thru 5 of time string of right_now
set the_secs to time of right_now
if (the_secs / 2 as integer) < 21600 then
set am_pm to "am"
else
set am_pm to "pm"
end if
set s to space
set text_date to the_day & s & short_month & ". " & the_year & s & short_time & am_pm
set the clipboard to text_date
my paste_date()
end run
on paste_date()
tell application "Numbers"
activate
tell application "System Events"
keystroke "v" using {command down}
end tell
end tell
end paste_date
This considers 11:59:59 to be "am" and 12:00:00 to be "pm". (Edited after further consideration.) It has to be run either as an Automator service, or saved in ~/Library/Scripts/Applications/Numbers/ and run from Numbers' script menu. If run from Script Editor, it pastes the date into the end of the script itself.
Hope it helps,
H -
Spawning pages with page numbers "page 1 of 1"
I'm using a calculation script to define "page 1 of 2" in a form. The script is as follows.
//set the page number to number 1
this.pageNum = 1;
//use the page of page format
event.value = "Page " + (event.target.page+1)+" of " + (this.numPages);
This works fine, however, when I start spawning pages the numbers get mixed up. For example, if I spawn one page, the "page 1 of 1" on page one changes to "page 1 of 2." On page two, it reads "page 0 of two." I just can't seem to get the "page n of n" to work with spawned pages. Any suggestions would help.
Thank youFor each page's field number page you need to go to that page in the calculation script. You could also turn off calculations during the spawning of the pages and then turn it back on and recalculate the form.
// code to spawn template;
// turn off automatic calculation;
this.calculate = false;
var t = this.templates;
var T = t[0];
T.spawn(this.numPages, true);
// trun automatic calculation back on;
this.calculate = true;
// force recalculation;
this.calculateNow();
// end spawn template;
// custom calculation script for numbering pages;
var cField = event.target.name;
var aField = cField.split(".");
if(aField.length > 1) {
// get page number for form field from field name & go to that page;
this.pageNum = aField[0].substr(1,1);
// update field's value;
event.value = (this.pageNum + 1) + " of " + this.numPages;
// update field's default value;
event.defaultValue = event.value;
// end custom calculation for numbering pages; -
How can i make the text go vertically in numbers
How can I make the text vertical in numbers? I have merged the cells and cannot find an option for making it go vertical as opposed to horizontal.
I already gave two tools to fit this kind of needs.
tip #1 :
--{code}
--[SCRIPT write_vertically]
Enregistrer le script en tant que Script : write_vertically.scpt
déplacer le fichier ainsi créé dans le dossier
<VolumeDeDémarrage>:Utilisateurs:<votreCompte>:Bibliothèque:Scripts:Applications :Numbers:
Il vous faudra peut-être créer le dossier Numbers et peut-être même le dossier Applications.
Saisir dans une cellule le mot à écrire verticalement puis le sélectionner.
ATTENTION, il ne faut pas sélectionner la cellule mais le mot qui doit apparaitre surligné.
Aller au menu Scripts , choisir Numbers puis choisir “write_vertically”
Le script colle dans la cellule le mot apès avoir inséré un return entre tous les caractères.
Pour mon usage personnel j'associe un raccourci à ce script grace à FastScripts.
--=====
L’aide du Finder explique:
L’Utilitaire AppleScript permet d’activer le Menu des scripts :
Ouvrez l’Utilitaire AppleScript situé dans le dossier Applications/AppleScript.
Cochez la case “Afficher le menu des scripts dans la barre de menus”.
Sous 10.6.x,
aller dans le panneau “Général” du dialogue Préférences de l’Éditeur Applescript
puis cocher la case “Afficher le menu des scripts dans la barre des menus”.
--=====
Save the script as a Script: write_vertically.scpt
Move the newly created file into the folder:
<startup Volume>:Users:<yourAccount>:Library:Scripts:Applications:Numbers:
Maybe you would have to create the folder Numbers and even the folder Applications by yourself.
In a cell, type a word to write vertically then select it.
CAUTION, don’t select the cell but the word which must be highlighted.
Go to the Scripts Menu, choose Numbers, then choose “write_vertically”
The script insert in the cell the word after inserting a return between every characters.
For my own use, I link a shortcut to the script thank to FastScripts.
--=====
The Finder’s Help explains:
To make the Script menu appear:
Open the AppleScript utility located in Applications/AppleScript.
Select the “Show Script Menu in menu bar” checkbox.
Under 10.6.x,
go to the General panel of AppleScript Editor’s Preferences dialog box
and check the “Show Script menu in menu bar” option.
--=====
Yvan KOENIG (VALLAURIS, France)
2011/12/17
2012/01/01 no longer use a local variable, use result
--=====
on run
Clear the clipboard *)
set the clipboard to ""
Copy the selection in the clipboard *)
my raccourci("Numbers", "c", "c")
Loop waiting that the clipboard is really filled *)
repeat
try
if (the clipboard as text) is not "" then exit repeat
on error
end try
end repeat
Extract the clipboard's content *)
the clipboard as text
Insert return between every characters *)
my recolle(every character of result, return)
Fill the clipboard with the edited string *)
set the clipboard to result
Paste in the cell *)
my raccourci("Numbers", "v", "cas")
end run
--=====
on recolle(l, d)
local oTIDs, t
set oTIDs to AppleScript's text item delimiters
set AppleScript's text item delimiters to d
set t to l as text
set AppleScript's text item delimiters to oTIDs
return t
end recolle
--=====
on activateGUIscripting()
(* to be sure than GUI scripting will be active *)
tell application "System Events"
if not (UI elements enabled) then set (UI elements enabled) to true
end tell
end activateGUIscripting
--=====
==== Uses GUIscripting ====
This handler may be used to 'type' text, invisible characters if the third parameter is an empty string.
It may be used to 'type' keyboard raccourcis if the third parameter describe the required modifier keys.
I changed its name « shortcut » to « raccourci » to get rid of a name conflict in Smile.
on raccourci(a, t, d)
local k
tell application a to activate
tell application "System Events" to tell application process a
set frontmost to true
try
t * 1
if d is "" then
key code t
else if d is "c" then
key code t using {command down}
else if d is "a" then
key code t using {option down}
else if d is "k" then
key code t using {control down}
else if d is "s" then
key code t using {shift down}
else if d is in {"ac", "ca"} then
key code t using {command down, option down}
else if d is in {"as", "sa"} then
key code t using {shift down, option down}
else if d is in {"sc", "cs"} then
key code t using {command down, shift down}
else if d is in {"kc", "ck"} then
key code t using {command down, control down}
else if d is in {"ks", "sk"} then
key code t using {shift down, control down}
else if (d contains "c") and (d contains "s") and d contains "k" then
key code t using {command down, shift down, control down}
else if (d contains "c") and (d contains "s") and d contains "a" then
key code t using {command down, shift down, option down}
end if
on error
repeat with k in t
if d is "" then
keystroke (k as text)
else if d is "c" then
keystroke (k as text) using {command down}
else if d is "a" then
keystroke k using {option down}
else if d is "k" then
keystroke (k as text) using {control down}
else if d is "s" then
keystroke k using {shift down}
else if d is in {"ac", "ca"} then
keystroke (k as text) using {command down, option down}
else if d is in {"as", "sa"} then
keystroke (k as text) using {shift down, option down}
else if d is in {"sc", "cs"} then
keystroke (k as text) using {command down, shift down}
else if d is in {"kc", "ck"} then
keystroke (k as text) using {command down, control down}
else if d is in {"ks", "sk"} then
keystroke (k as text) using {shift down, control down}
else if (d contains "c") and (d contains "s") and d contains "k" then
keystroke (k as text) using {command down, shift down, control down}
else if (d contains "c") and (d contains "s") and d contains "a" then
keystroke (k as text) using {command down, shift down, option down}
end if
end repeat
end try
end tell
end raccourci
--=====
--[/SCRIPT]
--{code}
tip #2 :
--{code}
--[SCRIPT rotate_cell_contents]
Enregistrer le script en tant que Script : rotate_cell_contents.scpt
déplacer le fichier ainsi créé dans le dossier
<VolumeDeDémarrage>:Users:<votreCompte>:Library:Scripts:Applications:Numbers:
Il vous faudra peut-être créer le dossier Numbers et peut-être même le dossier Applications.
Sélectionner une cellule dont le texte doit être tourné de 90 degrés.
Aller au menu Scripts , choisir Numbers puis choisir “rotate_cell_contents”
--=====
L’aide du Finder explique:
L’Utilitaire AppleScript permet d’activer le Menu des scripts :
Ouvrez l’Utilitaire AppleScript situé dans le dossier Applications/AppleScript.
Cochez la case “Afficher le menu des scripts dans la barre de menus”.
Sous 10.6.x,
aller dans le panneau “Général” du dialogue Préférences de l’Éditeur Applescript
puis cocher la case “Afficher le menu des scripts dans la barre des menus”.
--=====
Save the script as a Script: rotate_cell_contents.scpt
Move the newly created file into the folder:
<startup Volume>:Users:<yourAccount>:Library:Scripts:Applications:Numbers:
Maybe you would have to create the folder Numbers and even the folder Applications by yourself.
Select a cell whose contents must be rotated for 90 degrees.
Go to the Scripts Menu, choose Numbers, then choose “rotate_cell_contents”
--=====
The Finder’s Help explains:
To make the Script menu appear:
Open the AppleScript utility located in Applications/AppleScript.
Select the “Show Script Menu in menu bar” checkbox.
Under 10.6.x,
go to the General panel of AppleScript Editor’s Preferences dialog box
and check the “Show Script menu in menu bar” option.
--=====
Yvan KOENIG (VALLAURIS, France)
2011/06/23
2011/06/26 -- No longer use an auxiliary text box. Now keep the text attributes.
2012/01/31 -- edited for Lion
--=====
on run
local dName, sName, tName, rowNum1, colNum1, rowNum2, colNum2
local le_texte, la_largeur, la_hauteur, myNewDoc
my activateGUIscripting()
Extract properties of the source/target cell *)
set {dName, sName, tName, rowNum1, colNum1, rowNum2, colNum2} to my get_SelParams()
tell application "Numbers" to tell document dName to tell sheet sName to tell table tName
set selection range to range (name of column colNum1 & name of row rowNum1)
end tell
Cut*)
my raccourci("Numbers", "x", "c")
Trigger Preview *)
tell application "System Events"
if "Preview" is not in (name of every application process) then launch application "Preview"
end tell
delay 0.2 -- required
New document from the clipboard *)
my raccourci("Preview", "n", "c")
Rotate to left *)
my raccourci("Preview", "l", "c")
Copy *)
my raccourci("Preview", "c", "c")
Quit *)
my raccourci("Preview", "q", "c")
(system attribute "sys2") < 7
if result then
Click the [Don't Save] button in the warning sheet *)
tell application "Preview" to activate
tell application "System Events" to tell application process "Preview" to tell window 1
name of buttons
repeat 50 times
delay 0.1
if exists sheet 1 then exit repeat
end repeat
tell sheet 1 to click button 2
end tell
end if
Back to Numbers *)
tell application "Numbers" to tell document dName to tell sheet sName to tell table tName
-- just reset the focus on the table
end tell
Paste in the cell *)
my raccourci("Numbers", "v", "c")
end run
--=====
set { dName, sName, tName, rowNum1, colNum1, rowNum2, colNum2} to my get_SelParams()
tell application "Numbers" to tell document dName to tell sheet sName to tell table tName
on get_SelParams()
local d_name, s_name, t_name, row_num1, col_num1, row_num2, col_num2
tell application "Numbers" to tell document 1
set d_name to its name
set s_name to ""
repeat with i from 1 to the count of sheets
tell sheet i to set maybe to the count of (tables whose selection range is not missing value)
if maybe is not 0 then
set s_name to name of sheet i
exit repeat
end if -- maybe is not 0
end repeat
if s_name is "" then
if my parleAnglais() then
error "No sheet has a selected table embedding at least one selected cell !"
else
error "Aucune feuille ne contient une table ayant au moins une cellule sélectionnée !"
end if
Maybe you are looking for
-
PO editing after Goods receipt
We have the business requirement where the Goods receipt is done at Material transfer price (i.e. at Net price) where the material is loaded in vessel.When the actual physical goods come the PO is modified to accommodate the freight and customs and m
-
It´s possible to make different page sizes in the same document?
hi there familiy, I´m just learning InDesign (wich it´s fantastic) on line, and i ´d like to know how is possible to change 1 or few pages inside one document o make a flap (for example)? . But I want them to continue facing, to control de design. I
-
How do i write this in sql ? (another headcracker challenging report)
hi guys!, I need to create / generate a report. I intend to do all this with pure SQL alone. Been cracking my head for days but to no avail. Hope you gurus here will straightened me out. Here it goes. i Have a table TABLE USAGE_REPORT Date DATE -- ev
-
Upgrading Solaris 10 8/07 to run LDOMs?
I am trying to get to a point where I can create and run logical domains - the HW is a SPARC Enterprise T5220, OS is "Solaris 10 8/07 s10s_u4wos_12b SPARC" - and according to the book ("BEGINNERS GUIDE TO LDOMS: UNDERSTANDING AND DEPLOYING LOGICAL DO
-
IChat Network Error On Start Up
Hello, I have recently purchased a new MacBook Pro to replace my old iBook and with it came Leopard. Now, one problem I seem to have is when the computer starts up, everything is fine, until one error comes up and I think its iChat related, here is t