What MS Word 5.1 gaveth, subsequent MS Word versions tooketh away: the extremely useful ability to select text and have transfered to the clipboard the sum of all numbers contained within…ignoring line breaks, tabs, and alphabet characters, etc. Just the numbers.
This can’t be a hard applescript to write for someone good at such things…and I can’t imagine that everyone reading along wouldn’t want such a script on their system.
Has it been done? Anyone feel like doing it? Or giving me (a scripting newbie) some help?
This is actually quite easy to do with the following script:
tell application "Microsoft Word"
-- start off with 0
set sum to 0
-- get the selected text
set selectedText to (contents of selection) as string
-- loop through the words
repeat with aWord in (words of selectedText)
-- try loop to trap (ignore) errors
try
-- can we add this word to the sum?
set sum to sum + aWord
end try
end repeat
return sum
end tell
The concept here is to simply try adding all the words together as a sum. Clearly you can’t add a word to a number, so that generates an error. By including the code in a try/end try block you can trap the errors (and in this case ignore them). By extrapolation, any sum that does work (i.e. when the ‘word’ can be coerced to a number) increments the sum.
Hmm, that doesn’t work at all for me, and I’m not sure I’ve communicated well. I don’t want to add “words”…that wouldnt’ make sense. I want to just add all the numbers in the selection together, and put the total on the clipboard, as MS Word 5.1 used to do with its “Calculate” command.
Ideally, it’d work in bbedit or simpletext, etc, too.
It almost works but there is a problem considering negative numbers. For instance, look at this:
set sum to 0
set selectedText to "1 2 3 4 word 1 2 3 4 word -1"
repeat with aWord in (words of selectedText)
try
set sum to sum + aWord
end try
end repeat
return sum --> 21 instead of 19
I’d suggest ignoring/skipping negative numbers. Since this is working in a word processing environment, there’ll be all manner of dashes and hyphens to confuse the issue.
This is just a quickie to sum stuff; I think users would at very least be cautious in expecting it to recognize/handle negatives.