Accessing cells with offset reference in Numbers with Applescript - applescript

How can I reference a cell relative to another cell in Applescript like in Excel VBA?
In Excel VBA I could use "offset" to set the value of cell D2:
Range("A1").Offset(1,3).Value = "Example"
I searched everywhere but there doesn't seem to be an "offset"-command in Numbers Applescript, despite it's so super handy.
Any help is much appreciated!

To complement the excellent answer by David...
If you have a need to mimic the VBA expression, the example code from David's answer can be rolled into a handler, as in the example below.
on setCellOffsetValue(cl, co, ro, val)
tell application "Numbers"
tell table 1 of sheet 1 of document 1
set c to cell cl's column's address as number
set r to cell cl's row's address as number
set value of cell (c + co) of row (r + ro) to val
end tell
end tell
end setCellOffsetValue
Now you can use it multiple times in the same script by calling it, e.g.:
setCellOffsetValue("A1", 3, 1, "Example")
As you can see in this version, the setCellOffsetValue handler takes four parameters:
cl - The cell to offset from.
co - The column offset from the cell.
ro - The row offset from the cell).
val - The value of the offset cell.
Place the setCellOffsetValue handler within your script and call it as needed.
The handler above has table, sheet, and document hardcoded, each to 1. However, in this example you also pass that information to the handler:
on setCellOffsetValue(cl, co, ro, val, t, s, d)
tell application "Numbers"
tell table t of sheet s of document d
set c to cell cl's column's address as number
set r to cell cl's row's address as number
set value of cell (c + co) of row (r + ro) to val
end tell
end tell
end setCellOffsetValue
Now you can use it multiple times in the same script by calling it, e.g.:
setCellOffsetValue("A1", 3, 1, "Example", 1, 1, 1)
Or:
setCellOffsetValue("A1", 3, 1, "Example", "Table 1", "Sheet 1", "Untitled")
The last three parameters can be either their numeric value or name value, as appropriate for the need at that moment.
This version will be handy for documents that have multiple tables and or sheets and the need to target other then table 1 of sheet 1 of document 1.
As you can see in this version, the setCellOffsetValue handler takes seven parameters:
cl - The cell to offset from.
co - The column offset from the cell.
ro - The row offset from the cell).
val - The value of the offset cell.
t - The table number or name.
s - The sheet number or name.
d - The document number or name.
Note: The example AppleScript code is just that and does not contain any error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also Working with Errors.

Edit: Thanks to user3439894 for pointing out the problems with my first answer - it was totally wrong, based on Excel instead of Numbers.
Here's a full script example, showing one method to achieve the objective in Numbers:
tell application "Numbers"
tell table 1 of sheet 1 of document 1
set c to cell "A1"'s column's address as number
set r to cell "A1"'s row's address as number
set value of cell (c + 3) of row (r + 1) to "Example"
end tell
end tell
You could condense the set command into one line, like this:
tell application "Numbers"
tell table 1 of sheet 1 of document 1
set value of cell ((cell "A1"'s column's address as number) + 3) of row ((cell "A1"'s row's address as number) + 1) to "Example"
end tell
end tell

Related

Setting a variable in AppleScript based on a list in a Numbers sheet

AppleScript beginner here. Searching high and low hasn't led me to the answer yet.
I'm using AppleScript to help run youth wrestling tournaments. Each division (based on age) is broken down into weight classes. For example: Novice 80 or Cadet 105.
Once a certain group of kids is put into a certain division/weight class, those kids get added to a new sheet that contains their bracket (think March Madness bracket but a small number of kids wrestling instead of playing basketball).
I've figured out how to get a group into a new sheet where they populate the bracket, but when this new sheet is created, I don't know how to make AppleScript change the name of the sheet to the correct division/weight class. I'm sure it has something to do with creating variables based on a list of the divisions/weight classes (that I have), but I can't figure out how to do it. Here's the relevant portion of the code:
tell document 1
set active sheet to the last sheet
set thisSheet to make new sheet
set the name of thisSheet to "[Division variable – Weight class variable]"
tell thisSheet
delete every table
end tell
Any ideas on how to make AppleScript name the sheet like I want?
To give you a small example that you're able to visualize what you're going after, heres a small snippet. I think its self explanatory, iterate through a list of titles, then apply the names to the sheets.
set divisionNames to {"Novice", "Cadet"} -- How You Grab These Values Matters
set weightClasses to {"80", "105"} -- These Values Too
tell application "Numbers"
activate
set thisDocument to make new document
tell thisDocument
repeat with i from 1 to count of divisionNames
make new sheet with properties {name:item i of divisionNames & space & item i of weightClasses}
end repeat
end tell
end tell
Alternately, if you're pulling the values from a list as a whole then you could
set sheetTitles to {"Novice 80", "Cadet 105"}
tell application "Numbers"
activate
set thisDocument to make new document
tell thisDocument
repeat with division in sheetTitles
make new sheet with properties {name:division}
end repeat
end tell
end tell
EDIT: In the spirit of helping a low to no budget school/organization.. here's another example answering the second question issued in comments. Again without knowing the structure of your data its hard to give you an exact answer on your specific case. Additionally, here's a link to a site they may help further the advancement on your project. https://iworkautomation.com/numbers/index.html
(*
set sampleKids to {"John Doe", "Jane Doe", "Johnny Foe", "Janie Foe", "Tommy Joe", "Tammy Joe"}
set sampleDivisions to {"Novice-80", "Novice-85", "Cadet-105", "Cadet-110", "Novice-80", "Cadet-105"}
tell application "Numbers"
activate
set thisDoc to make new document with properties {name:"Wrestling Sample"}
tell thisDoc
set the name of sheet 1 to "Sign In Sheet"
tell active sheet
delete every table
set newTable to make new table with properties {row count:(count of sampleKids) + 1, column count:2, name:"Sign In Sheet"}
tell newTable
set value of cell 1 of column "A" to "Name"
set value of cell 1 of column "B" to "Division"
set x to 2
repeat with eachName in sampleKids
set value of cell x of column "A" to eachName
set x to (x + 1)
end repeat
set x to 2
repeat with eachDivision in sampleDivisions
set value of cell x of column "B" to eachDivision
set x to (x + 1)
end repeat
end tell
end tell
end tell
end tell
*)
--********** IGNORE ABOVE THIS LINE IT'S ONLY BUILDING A SAMPLE TABLE **********--
--********** SAVE ABOVE TO ANOTHER SCRIPT FOR TESTING WITH NEW TABLE **********--
(*
ERROR HANDLING ISN'T PRESENT - AN EMPTY CELL IN FIRST COLUMN OR CHOSEN COLUMN WILL THROW AN
ERROR SINCE THEY ARE THE IMPORTANT PIECES OF DATA FOR GRABBING LISTS - SAVE SCRIPT
TO NUMBERS SCRIPT FOLDER OF YOUR CHOICE - ENTER ALL INFO ON FIRST TABLE OF FIRST SHEET OF
DOCUMENT THEN RUN SCRIPT - SCRIPT ACCEPTS ANY AMOUNT OF ROWS OR COLUMNS
*)
tell application "Numbers"
activate
-- Display A Simple Reminder That You're About To Lose Some Existing Data
display dialog "This Script Will Delete All Sheets Except The First Sheet Of This Document Before It Proceeds To Make New Sheets & Tables Based On The First Table Of The First Sheet." buttons {"Cancel", "Start"} default button 2 with icon 1
tell document 1
-- Get A List of the Sheet Names
set sheetNames to name of sheets
-- Start With A Fresh Slate, No Old Sheets
delete (every sheet whose name is not item 1 of sheetNames)
tell sheet 1
-- Grab and Set Future Header Values
set columnHeaders to value of cell of row 1 in table 1
-- Display A List Of Possible Choices To Create New Sheets With From The List We Make Above
set chosenColumn to choose from list columnHeaders with prompt "Which Column Do You Want To Use For New Sheets?" default items item 1 of columnHeaders
set chosenColumn to chosenColumn as text
tell table 1
-- Remove All Empty Rows to Help Prevent Error In Script
set {row_count, col_count} to {count rows, count columns}
set blank_row to {}
repeat with x from 1 to col_count
set blank_row to blank_row & missing value
end repeat
set x to 1
-- Delete Empty Rows In Reverse, It's Logical
repeat with y from row_count to 1 by -1
set row_values to value of cells of row y
if row_values = blank_row then delete row y
end repeat
-- Grab A List of All Divisions for Future Use Depending on Choice From Prompt, excluding the First Row Which Is A Header. If You Selected The First Column, We Have to Handle That Differently
if chosenColumn is item 1 of columnHeaders then
set theDivisions to the value of every cell of column "A" whose value is not chosenColumn
else
set theDivisions to the value of every cell of column named chosenColumn whose value is not chosenColumn
end if
end tell
end tell
-- Start the New "Sheet Making" Loop
repeat with division in theDivisions
-- Make An Empty Blank List At the Start of Every Loop
set matchingDivisions to {}
tell table 1 of sheet 1
-- Get All Rows Matching the Current Division of the Loop We Are On, to Make New Tables With Later
repeat with x from 1 to count of cells
if the value of cell x is division then
-- Put All Data About the Rows We Gathered Above Into the Empty List We Made
set the end of matchingDivisions to value of cells of row of cell x
end if
end repeat
-- Reset x, Because I'm Not Creative and Want to Use It Later
set x to 1
end tell
-- If The Sheet Of the Division We Are On, of the Loop, Doesn't Exist, Make It
if not (exists sheet division) then
make new sheet with properties {name:division}
tell sheet division
-- Start With A Fresh Slate On This New Sheet
delete every table
-- Make the Table With All Relevant Parameters
set currentDivisionTable to make new table with properties ¬
{row count:((count of matchingDivisions) + 1), column count:count of item 1 of matchingDivisions, name:division}
tell currentDivisionTable
set x to 1
-- Set The Header Values from A List We Created Earlier
repeat with theHeader in columnHeaders
set the value of cell x to theHeader
set x to (x + 1)
end repeat
-- Reset x Again, I'm Lazy
set x to 1
-- Set Starting Point to Start Filling The Table, Compensate For Our Headers
set rowIndex to 1
set columnIndex to 0
-- Start Filling The Table With Data, Which Comes From The List Earlier
repeat with x from 1 to count of the matchingDivisions
set rowData to item x of the matchingDivisions
tell row (rowIndex + x)
repeat with i from 1 to the count of rowData
tell cell (columnIndex + i)
set value to item i of rowData
end tell
end repeat
end tell
end repeat
end tell
end tell
end if
end repeat
-- Return To the First Sheet
set the active sheet to the first sheet
-- Display Notification That The Tables Are Done Being Made -- OPTIONAL
display notification "Processing is complete." with title "Numbers Table Converter" subtitle "All Tables Have Been Made." sound name "Hero"
end tell
end tell
Try
set thisSheet to make new sheet with properties {name:"yourname"}
Edit
Some explanation: if your struggling on how to adress third party apps try to load it's library and look up the methods you need. In applescript editor you will find it in the (I guess) menu. Then select the desired app to get the library
The full code modify at below:
set {begCol, endCol} to {2, 17}
set tgtCol to 1
tell application "Numbers"
tell front sheet of front document
tell active sheet
set getVal to rows's cells's value
set myOriginalTable to front table
set itemCode to {"CardNo", "SAL-DAY", "OT15-Money",
"OT2-Money", "OT3-Money", "OTHINC", "P0007", "DILIG", "P0004", "P0003",
"SEV_SPE", "P0011", "SI-SSF", "TI-TAXITEM", "P0022", "P0021", "P0025"} --
change to variable
set Amount to {"CardNo", "SAL-DAY", "OT15-Money",
"OT2-Money", "OT3-Money", "OTHINC", "P0007", "DILIG", "P0004", "P0003",
"SEV_SPE", "P0011", "SI-SSF", "TI-TAXITEM", "P0022", "P0021", "P0025"} --
change to variable
set setCols to 8
end tell
set myNewTable to make new table with properties ¬
{column count:setCols, row count:(count of itemCode) + 1,
header column count:0}
tell myNewTable
set value of cell 1 of column "A" to "cardNo"
set value of cell 1 of column "B" to "emCode"
set value of cell 1 of column "C" to "emName"
set value of cell 1 of column "D" to "itemCode"
set value of cell 1 of column "E" to "itemName"
set value of cell 1 of column "F" to "effDate"
set value of cell 1 of column "G" to "amt"
set value of cell 1 of column "H" to "remark"
set x to 2
repeat with eachAmount in Amount
set value of cell x of column "G" to eachAmount
set x to (x + 1)
end repeat
set x to 2
repeat with eachItemCode in itemCode
set value of cell x of column "D" to eachItemCode
set x to (x + 1)
end repeat
end tell
end tell
end tell
Thank you
According source code above. I found other way for use range select for determine data. But it still incorrect because the code pickup all data to one cell like this.
result after ran script
Could some one able to suggest me?
try
tell application "Numbers" to tell front document to tell active sheet
set delimiter to ","
set selected_table to first table whose class of selection range is range
tell selected_table
set my_selection to the selection range
set begCol to address of first column of my_selection
set endCol to address of last column of my_selection
set begRow to address of first row of my_selection
set endRow to address of last row of my_selection
set getVal to ""
repeat with j from begRow to endRow
repeat with i from begCol to endCol
set getVal to (getVal & (value of cell j of column i of selected_table) as text) & delimiter
set getVal to getVal & return
end repeat
end repeat
end tell
end tell
set AmountVal to {getVal}
tell application "Numbers"
activate
tell front sheet of front document
set myOriginalTable to front table
set setCols to 8
set myNewTable to make new table with properties ¬
{row count:(count of AmountVal) + 1, column count:setCols, header column count:0}
tell myNewTable
set value of cell 1 of column "A" to "cardNo"
set value of cell 1 of column "B" to "emCode"
set value of cell 1 of column "C" to "emName"
set value of cell 1 of column "D" to "itemCode"
set value of cell 1 of column "E" to "itemName"
set value of cell 1 of column "F" to "effDate"
set value of cell 1 of column "G" to "amt"
set value of cell 1 of column "H" to "remark"
set x to 2
repeat with eachAmount in AmountVal
set value of cell x of column "G" to eachAmount
set x to (x + 1)
end repeat
end tell
end tell
end tell
display notification "Already Done!" with title "Numbers"
on error
display dialog "Select a range first and then try again"
end try

Change All Value Labels to Numerics in SPSS

I need to change all the value labels of all my variables in my spss file to be the value itself.
I first tried -
Value Labels ALL.
EXECUTE.
This removes the value labels, but also removes the value entirely. I need this to have a label of some sort as I am converting the file and when there is no values defined it turns the value into a numeric. Therefore, I need the all value labels changed into numbers so that each value's label is just the value - value = 1 then label = 1.
Any ideas to do this across all my variables??
Thanks in advance!!
Here is a solution to get you started:
get file="C:\Program Files\IBM\SPSS\Statistics\23\Samples\English\Employee data.sav".
begin program.
import spss, spssaux, spssdata
spss.Submit("set mprint on.")
vd=spssaux.VariableDict(variableType ="numeric")
for v in vd:
allvalues = list(set(item[0] for item in spssdata.Spssdata(v.VariableName, names=False).fetchall()))
if allvalues:
cmd="value labels " + v.VariableName + "\n".join([" %(i)s '%(i)s'" %locals() for i in allvalues if i <> None]) + "."
spss.Submit(cmd)
spss.Submit("set mprint off.")
end program.
You may want to read this to understand the behaviour of fetchall in reading date variables (or simply exclude date variables from having their values labelled also, if they cause no problems?)

Using AppleScript, how to set the value of a cell of the Numbers App/iWork file

Using the numbers file below, how do i set a value into cell B2?
The hard part is that i cannot use any of the code below:
set the value of cell 2 of column "B" to "200.00"
or
set the value of cell "B2" to "200.00"
Based on the requirements, i have to find the row and the column because their positions can change.
I have got this part to work:
set the value of cell 2 of column of (first cell of row 1 whose value is "SUM") to "200.00"
Now I'm trying to get rid of the cell 2 in the code above. I can't figure it out. Any help will be much appreciated.
You can use the header's name like this :
tell application "Numbers"
tell table 1 of sheet 1 of document 1
set colIndex to address of column "SUM"
set value of cell colIndex of row "Jan" to "200.00"
end tell
end tell

Applescript Error "can't get end of"

I am trying my hand at Applescript and can't see anything wrong with this.
The Error I get is
error "Can’t get end of {button returned:\"OK\", text returned:\"3\"}." number -1728 from last insertion point of {button returned:"OK", text returned:"3"}
This is my code:
beep
set counter to 0
set tempX to 0
set temp to 0
set counting to 0
set stored to {0}
set input to "How many grades do you wish to enter?" as string
set str to display dialog input buttons {"NEXT"} default button "NEXT" default answer ""
repeat text returned of str times
counting = counting + 1
set grades to display dialog "GRADES: " default answer ""
set stored to grades
end repeat
set rep to the length of stored
repeat rep times
counter = counter + 1
set tempX to the ((end of stored) - counter) as number
set temp to temp + tempX
end repeat
set ln to the length of grades
set average to temp / ln
if text returned of str is 1 then
say "The Average of your grade is " & average using "Zarvox"
else
say "The Average of your grades is " & average using "Zarvox"
end if
get "AVERAGE: " & average
So, before I begin: I'd strongly recommend that you teach yourself how to use the Javascript interface to Apple Events, rather than the Applescript language itself. Applescript is a really weird language, and its quirks are largely unique; learning it is going to be frustrating, and won't help you learn other languages.
That being said, let's dive into your code:
set stored to {0}
This would start you out with one grade that's always present and set to zero. You probably want to just initialize this to an empty list:
set stored to {}
Next:
set grades to display dialog "GRADES: " default answer ""
This sets grades to a result object, not just the answer. What you probably want here is actually the text returned of the result:
set grades to text returned of (display dialog "GRADES: " default answer "")
(This is what's creating the really weird-looking object in your error message.)
Next, you overwrite stored with this result object:
set stored to grades
What you probably want here is to insert this element into the list. Because Applescript is a strange and obnoxious language, this is somewhat more cumbersome than you're thinking:
set stored to stored & {grades}
Finally, there's some logical issues with your averaging; you're adding the end of stored (that is, the last grade input) to the temp variable each time. A much simpler approach would be:
set temp to 0
repeat with n in stored
set temp to temp + n
end repeat
set average to sum / (count of stored)
With these changes all made, your script should work correctly.

Excel Mac VBA Loop Through Cells and reset some values

I currently have a worksheet that I have multiple people filling out every day. There are 4 columns that the users fill out: C, E, H, & J (all numerical values, one row per day of the month.)
The users fill in C, E, & H every day no matter what, but a lot of days there is no value to put in column J. I need the value in J to be set to 0 if the user doesn't enter anything. Of course it would be easier to just have the users enter 0, but I'm working with a complicated group of people here.
Anyway, I want to use a macro that runs automatically when the user clicks the save button (before it actually saves, of course), and have it do the following: (I am more familiar with php, so I'm just typing this out how I'm familiar - I'm sure my syntax is incorrect)
Foreach Row
If "column A" != "" {
If "column J" != "" {
//Everything is good, continue on...
} else {
CurrentRow.ColumnJ.value == 0
}//Value has been set - continue loop
}
//column A is blank, this day hasn't come yet - quit looping here
End Foreach
If anyone could help me out with this I'd appreciate it. With some research, this is what I've come up with so far, and now I'm stuck…
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim curCell As Range
'Labor Flow Sheet'.Select
For Each curCell in Range( ???? )
If curCell.Value = "" Then
???????
End If
Next curCell
End Sub
Thanks in advance!
See this link about finding the right range, and as for the question marks inside the If statement, you would want to put
curCell.Value = 0
For the question marks in your statement
For Each curCell in Range( ???? )
Solution 1:
To find the full range you're working with, you'll need to use a column that is filled out each day. You mentioned columns C, E, and H were filled out every day. Using one of those columns (let's pick C for the example here), you could find the range by using the .end method. This goes out either up down left or right from a range until it doesn't find any data. So,
Range("J1", Range("C1").End(xlDown)).Select
will select all cells from J1 (or whatever column is the last in your sheet) to the bottom-most cell containing data in column C, automatically.
Solution 2:
Manually put in the range. For example, to choose A1 to J300:
Range("A1", "J300").Select

Resources