Can Apple Script find/replace for conditions in formulas within cells?

I asked ChatGPT (who is writing the apple script for me) how to even phrase this question and here's what Chat suggested:


I'm using AppleScript to replace part of a COUNTIFS formula in a Numbers table. The original formula refers to columns in another table by name (e.g., Data Table::$Author).

When I manually enter or paste this formula in the Numbers UI, the app highlights each column reference as a color-coded token — confirming that it has resolved them to actual columns.

However, when I assign the exact same formula string using AppleScript (via set formula or set value), Numbers either:

  • throws error -10003, or
  • accepts the formula as text but fails to interpret the column references correctly.

This suggests that AppleScript-injected formulas are not being parsed through the same semantic resolution engine as user-entered formulas.

Is there a way to ensure that AppleScript-submitted formulas are parsed with full table/column binding, like user-entered ones?

iMac 27″ 5K, macOS 13.7

Posted on Mar 31, 2025 1:10 AM

Reply
27 replies
Sort By: 

Mar 31, 2025 12:18 PM in response to anotherjas

anotherjas wrote:

So I tried to run your script and am stuck at the same syntax error message for the one cell it attempted to replace:
The good syntax looks like this:
COUNTIFS(Data Table::$Total 5@,"=5",Data Table::$clause 0,"=B0-D12*",Data Table::$Author,"=Pl")
and appears like this:

https://discussions.apple.com/content/attachment/284891aa-db8c-4588-80f7-ccf1713c3382

the substitution that gets the syntax error message looks like this:

COUNTIFS(Data Table::$Total 5@,"=5",Data Table::$clause 0,"=B0-D12*",Data Table::$Author,"=T")


They look the same to me! Can you spot a difference. Maybe Numbers is getting confused by multiple tables in that document with duplicate column headers? Simplify down to isolate the problem.


SG

Reply

Mar 31, 2025 11:45 AM in response to anotherjas

anotherjas wrote:

All I want is an updated formula that looks for T rather than Pl in the Author column. Chat worried about deeper troubles.


Yes all the special characters can confuse machines (and humans).


If all you want to do is replace =PI with =T in a bunch of formulas then you can use this 'Find Replace in Formulas' Shortcut I made a while ago.


https://www.icloud.com/shortcuts/e52edb6b10084a93a7f030f03e2eff30


Click the link in Safari to view the AppleScript and, if you like, install the Shortcut. It can be run from the Shortcuts app or pinned to the Menu Bar and run from there.


To use:


  1. Select the cells with formulas that you want to change.
  2. Run the shortcut (it can be pinned to menu bar)
  3. Answer the first prompt with: =PI
  4. Click Next
  5. Answer the second prompt with: =T.
  6. Click OK.


This changes the values in the target cells, so make a backup before running to make sure it is giving you the results that you want.


SG



Reply

Mar 31, 2025 1:59 PM in response to anotherjas

That's strange. Maybe the special characters confuse the parser.


Something more things to try -


  • Go to Numbers > Settings and deselect 'Use header names as labels'.
  • If you haven't done so already restart your Mac.
  • Deactivate any special utilities you may have added on your Mac.


SG

Reply

Mar 31, 2025 8:42 AM in response to anotherjas

Congratulations on experimenting with AI to help with writing scripts. In my experience it is far from perfect. But it can give you approaches you might not have considered on your own and can help save HOURS of time!


A -10003 error is a permissions error. If you're still seeing that, then make sure you have set permissions at System Settings > Security & Privacy > Privacy > Automation and that the target Numbers document is open.


Not sure what you mean by "accepts the formula as text but fails to interpret the column references correctly." Do you mean the formula is entered successfully in the cell but appears as text there and doesn't work. If so it could be that the cell is formatted as Text instead of Automatic. Here is a simple working script that first sets the format to Automatic:


tell application "Numbers"
	tell front document
		tell sheet 1
			tell cell "B2" of table "Table 1"
				set format to automatic
				set value to "=COUNTIF(Data Table::B,A2)"
			end tell
		end tell
	end tell
end tell


Result:








If you haven't done so already you can pick up ideas from this site, in particular this example, which uses AppleScript to set a COUNTIF formula ("use of contextual formulas"- line 144)


https://iworkautomation.com/numbers/examples-attendance.html



SG







Reply

Mar 31, 2025 10:48 AM in response to Camelot

So, the problem: two tables in one sheet, one table with data, the other table to collect information from the data via lots of different COUNTIFS formulae in 400+ cells. Each of the COUNTIFS ends with the test-value of a column (in the data table), and a condition, "=Pl". (i.e. find the text string Pl). Works great.

Now I have duplicated that sheet, renamed the sheet with a new title, and in this new sheet, I'm trying to find/replace every instance of the condition "=Pl" to the new condition "=T" (i.e. find every instance of T instead of Pl)


I asked ChatGPT to do the scripting for me (which I could never have figured out on my own). And Chat got pretty close, without being able to jump the final hurdle of getting Numbers to understand the test-value locations in the data table.


So the correct answer (offering just one cell as an example) is supposed to look like this:



But what Chat's AppleScript produced (and caused an error message in every cell where the replacement happened) this:


COUNTIFS(Data Table::$Total 5@,"=5",Data Table::$clause 0,"=B0-D12*",Data Table::$Author,"=T")


The formula is letter perfect, but Numbers can't read the addresses in that formula (i.e. can't recognize the columns where it should look)


And, because you asked, I'm sharing Chat's script that moved through 400 cells and replaced every instance of Pl with a T:



tell application "Numbers"

activate

tell document "Correlation scratch sheet.numbers"

tell sheet "All Septenarii Terence"

tell table "Table 3"

set rowCount to row count

set columnCount to column count


repeat with r from 1 to rowCount

repeat with c from 1 to columnCount

tell cell c of row r

try

set cellFormula to formula


if cellFormula contains "Pl" then

log "Row " & r & ", Col " & c

log "Original: " & cellFormula


-- Replace "Pl" with "T"

set updatedFormula to my replaceText("Pl", "T", cellFormula)


-- Remove quotes around table names (restore to unquoted)

set updatedFormula to my unquoteTableNames(updatedFormula)


-- Unescape any internal quotes (remove \")

set finalFormula to my replaceText("\\\"", "\"", updatedFormula)


log "Final: " & finalFormula


-- Set the final cleaned formula

set value to finalFormula

end if


end try

end tell

end repeat

end repeat

end tell

end tell

end tell

end tell


-- Replace text utility

on replaceText(findText, replaceWith, sourceText)

set AppleScript's text item delimiters to findText

set textItems to every text item of sourceText

set AppleScript's text item delimiters to replaceWith

set newText to textItems as string

set AppleScript's text item delimiters to ""

return newText

end replaceText


-- Convert 'Data Table' → Data Table (remove quotes from table name)

on unquoteTableNames(formulaText)

set cleanedFormula to formulaText

set referenceList to {"'Data Table'::$CI", "'Data Table'::$clause 0", "'Data Table'::$clause 2", "'Data Table'::$Author", "'Data Table'::$Total 5@"}


repeat with refItem in referenceList

set unquotedRef to my unquoteTableOnly(refItem as text)

set cleanedFormula to my replaceText(refItem, unquotedRef, cleanedFormula)

end repeat


return cleanedFormula

end unquoteTableNames


-- Convert 'Table'::$Column → Table::$Column

on unquoteTableOnly(rawRef)

if rawRef contains "'::$" then

set AppleScript's text item delimiters to "'::$"

set parts to every text item of rawRef

set tableName to item 1 of parts

set columnName to item 2 of parts

set AppleScript's text item delimiters to ""

return tableName & "::$" & columnName

else

return rawRef

end if

end unquoteTableOnly


Reply

Mar 31, 2025 11:21 AM in response to SGIII

Thank you, SG, for your interest.


Here's a screenshot of part of the data table:


and here's the right hand side of the table (with other columns of interest):


Sorry it's so small--it's a big data table. But it's interesting that Chat had to work out what do with my (naively) using characters like "$" and "@" in my data. All I want is an updated formula that looks for T rather than Pl in the Author column. Chat worried about deeper troubles.


JAS

Reply

Mar 31, 2025 12:10 PM in response to SGIII

So I tried to run your script and am stuck at the same syntax error message for the one cell it attempted to replace:

The good syntax looks like this:

COUNTIFS(Data Table::$Total 5@,"=5",Data Table::$clause 0,"=B0-D12*",Data Table::$Author,"=Pl")

and appears like this:


the substitution that gets the syntax error message looks like this:


COUNTIFS(Data Table::$Total 5@,"=5",Data Table::$clause 0,"=B0-D12*",Data Table::$Author,"=T")

Reply

Mar 31, 2025 12:39 PM in response to anotherjas

So, running SG's shortcut, here's the cell before I run the shortcut:



And here's the cell after I run the shortcut:



and the cell contains this:



Isn't there some magical command to get Numbers to re-evaluate the table?


and, thank you, everybody, for sticking with me on this. It's an essential problem I'd love to master, but at some point, when you've all become exasperated, I'll just manually enter T in 400 cells.


JAS

Reply

Mar 31, 2025 4:27 AM in response to anotherjas

The short test script given below works fine. I do not know what ChatGPT provided to you but teaching ChatGPT how to code is not on my bucket list. My educated guess is it gave you trash.



tell application "Numbers"
	tell document 1 to tell sheet 1 to tell table 1
		set value of cell "B2" to "=Data Table::$Author"
	end tell
end tell

Reply

Mar 31, 2025 10:28 AM in response to SGIII

Thank you, SG, for your encouragement and sample script, and for your web link for lots more examples.


See below where I've actually pasted ChatGPT (4.5)'s suggestion for how to move through a table with 400+ cells, looking to replace one element of the formula.


JAS

Reply

Mar 31, 2025 11:21 AM in response to anotherjas

And if you think the formula is exactly right except that Numbers is not recognizing it as a formula then before you do anything else you could try putting this line directly before 'set value to finalFormula':


set format to automatic


SG

Reply

Mar 31, 2025 11:22 AM in response to anotherjas

The script looks a little verbose, but functional. Indeed, on my machine (assuming I recreated your Data Table accurately enough, it seems to work for me - replacing the formula:


=COUNTIFS(Data Table::$Total 5@,"=5",Data Table::$Clause 0,"=B0-D12*",Data Table::$Author,"=Pl")


with


=COUNTIFS(Data Table::$Total 5@,"=5",Data Table::$Clause 0,"=B0-D12*",Data Table::$Author,"=T")


So the two questions are:


What do you get in the field after the script runs? Can you copy the result from your sheet to this thread?


What does the script log for finalFormula?


(for speed, you can change the lines:


				set rowCount to row count
				set columnCount to column count


to:


				set rowCount to 1
				set columnCount to 1


for test, so it doesn't have to update the entire sheet, just the first row/column. That will help both speed it up, and limit the log output to help find the answer.

Reply

Mar 31, 2025 11:50 AM in response to Camelot

Thank you both, SG and Camelot, for your interest. Here's Chat's attempt to fix just a single formula in one cell:


tell application "Numbers"

activate

tell document "Correlation scratch sheet.numbers"

tell sheet "All Septenarii Terence"

tell table "Table 3"

tell cell 3 of row 2

try

set formula to "COUNTIFS(Total 5@, \"=5\", clause 0, \"=B0-D12*\", Author, \"=T\")"

log "✅ Formula successfully assigned"

on error errMsg number errNum

log "❌ Error setting formula: " & errMsg & " (Error " & errNum & ")"

end try

end tell

end tell

end tell

end tell

end tell



and here is the error message that was logged in the script editor:


tell application "Numbers"


activate


set formula of cell 3 of row 2 of table "Table 3" of sheet "All Septenarii Terence" of document "Correlation scratch sheet.numbers" to "COUNTIFS(Total 5@, \"=5\", clause 0, \"=B0-D12*\", Author, \"=T\")"


--> error number -10003 from formula of cell to any


(*❌ Error setting formula: Numbers got an error: Can’t set formula of cell to "COUNTIFS(Total 5@, \"=5\", clause 0, \"=B0-D12*\", Author, \"=T\")". (Error -10006)*)


end tell

Reply

Mar 31, 2025 12:04 PM in response to anotherjas

You're missing the leading = sign.


...

set formula to "=COUNTIFS(Total 5@, \"=5\", clause 0, \"=B0-D12*\", Author, \"=T\")"

...


The leading = is needed to indicate a formula vs. a static text field.


That shouldn't affect the original script, though, since the = should have been included when you extract the cells' current formula, and therefore should have still been present when you push the data back.


Reply

Can Apple Script find/replace for conditions in formulas within cells?

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.