Extreme Hang In A Repeat Loop - applescript

With my script for a Numbers table, I am experiencing an extreme (3-4 seconds per cell) hang in a repeat loop, which I believe may be caused by my use of the copy command, since as I understand it,copy creates a new reference to the value, instead of replacing the value like the set command would. I am unsure if its the use of the copy command, my Mac, or poor placement of the loop in the sequence of commands. I've tried switching the sequence of commands around which doesn't help. Other uses of a similar copy loop do not behave so slowly. My question is sort of a compound question. Am I asking the loop to process to much, is it misplaced, should I be using something other than copy or is it simply my Mac? (memory doesn't appear to be low enough to cause the hang, still 1.5gb left during the hang, nothing except Numbers and the script running) To sum it up, how can I solve the hang issue?
The portion of the loop where the hang begins is below
-- This is where the extreme hang begins
repeat with x from 1 to (count rows) - 2
repeat with y from 1 to count monthNames
copy incrementDates(y) of me to {theDayIndex, theMonthIndex, theYear, theDateString, monthLengthInDays}
set monthStart to theDateString
set monthEnd to theMonthIndex & "/" & monthLengthInDays & "/" & theYear as text
set theFormula to "=SUMIFS(Amount,Category,A,Date, \">=" & monthStart & "\",Date, \"<=" & monthEnd & "\")"
set value of cell (y + 1) of row (x + 1) to theFormula
end repeat
end repeat
-- Extreme hang ends and script continues normally
The full script for reference is here, in case its a compounded issue of my other copy usage.
set moneyInHeaders to {"Last Name", "First Name", "Receipt Number", "Payment", "Date", "Office", "City", "Referral Name"}
set locationList to {"Location 1", "Location 2"}
set the monthNames to {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
set moneyOutHeaders to {"Expense", "Amount", "Date", "Category", "Item"}
set categoryItems to {"Marketing", "Software", "Tools", "Utilities", "Other"}
set thisYearName to (year of (current date)) as string
set moneyInColor to {31354, 51657, 22615}
set moneyOutColor to {59623, 20816, 14391}
tell application "Numbers"
if not (exists document 1) then make new document
tell document 1
delete every sheet
set the name of sheet 1 to "Money In"
tell sheet 1
delete every table
set moneyInTable to make new table with properties {name:"Money In", position:{-7, 29}, width:788, column count:count moneyInHeaders, row count:14, footer row count:1, header column count:2}
tell moneyInTable
set locationCount to count locationList -- get count of locations
set properties of row 1 to {background color:{moneyInColor}}
my populateCells(moneyInTable, row 1, moneyInHeaders, false) -- fill header row values
set value of last cell of column named "Payment" to ("=SUM(C)")
my populateCells(moneyInTable, column named "Office", locationList, true) -- fill pop up menu values
my formatCells(moneyInTable, column named "Payment", currency)
my formatCells(moneyInTable, column named "Date", date and time)
my formatCells(moneyInTable, column named "Office", pop up menu)
delete (rows 2 through (locationCount + 1)) -- remove rows that contain values so the pop up column is empty
repeat locationCount times -- add the rows back to keep table size
add row below row 2
end repeat
end tell -- end telling moneyInTable
-- Set locked false for now
set totalsTable to make new table with properties {name:"Money In Totals", locked:false, position:{785, 29}, column count:2, row count:(count monthNames) + 2, header column count:1, header row count:1, footer row count:1}
tell totalsTable
set properties of row 1 to {background color:{moneyInColor}}
my populateCells(totalsTable, column "A", monthNames, true)
set value of last cell of column "A" to "Grand Total"
set value of cell "B1" to "Totals"
set value of last cell to ("=SUM(B)")
tell column "B"
repeat with x from 1 to count monthNames -- loop and increment dates for the SUMIFS formula
copy incrementDates(x) of me to {theDayIndex, theMonthIndex, theYear, theDateString, monthLengthInDays}
set monthStart to theDateString
set monthEnd to theMonthIndex & "/" & monthLengthInDays & "/" & theYear as text
set the value of cell (x + 1) to ("=SUMIFS(Payment,Date, \">=" & monthStart & "\", Date, \"<=" & monthEnd & "\")")
end repeat
end tell -- end telling column B
end tell -- end telling totalsTable
end tell -- end telling active sheet
make new sheet with properties {name:"Money Out"}
tell sheet 2
delete every table
set moneyOutTable to make new table with properties {name:"Money Out", position:{-7, 29}, width:710, column count:count moneyOutHeaders, row count:14, footer row count:1}
tell moneyOutTable
set catCount to count categoryItems -- get count of categoryItems
set properties of column "A" to {width:180}
set properties of row 1 to {background color:{moneyOutColor}}
set value of last cell of column "B" to ("=SUM(B)")
my populateCells(moneyOutTable, row 1, moneyOutHeaders, false) -- fill header row values
my populateCells(moneyOutTable, column named "Category", categoryItems, true) -- fill pop up values
my formatCells(moneyOutTable, column "A", text)
my formatCells(moneyOutTable, column named "Amount", currency)
my formatCells(moneyOutTable, column named "Date", date and time)
my formatCells(moneyOutTable, column named "Category", pop up menu)
my formatCells(moneyOutTable, column named "Item", text)
delete (rows 2 through (catCount + 1)) -- remove rows that contain values so the pop up menu is empty
repeat catCount times -- add the rows back to keep table size
add row below row 2
end repeat
end tell -- end telling moneyOutTable
set totalsTable to make new table with properties {name:"Money Out Totals", locked:false, position:{744, 29}, column count:2, row count:(count monthNames) + 2, header column count:1, header row count:1, footer row count:1}
tell totalsTable
set properties of row 1 to {background color:{moneyOutColor}}
my populateCells(totalsTable, column "A", monthNames, true)
set value of last cell of column "A" to "Grand Total"
set value of cell "B1" to "Totals"
set value of last cell to ("=SUM(B)")
tell column "B"
repeat with x from 1 to count monthNames -- oop and increment dates for the SUMIFS formula
copy incrementDates(x) of me to {theDayIndex, theMonthIndex, theYear, theDateString, monthLengthInDays}
set monthStart to theDateString
set monthEnd to theMonthIndex & "/" & monthLengthInDays & "/" & theYear as text
set theFormula to ("=SUMIFS(Amount,Date, \">=" & monthStart & "\", Date, \"<=" & monthEnd & "\")")
set the value of cell (x + 1) to theFormula
end repeat
end tell -- end telling column B
end tell -- end telling totalsTable
set summaryTable to make new table with properties {name:"Category Totals", position:{943, 29}, column count:2, row count:(catCount) + 1}
tell summaryTable
set properties of row 1 to {background color:{moneyOutColor}}
set value of cell "B1" to "Totals"
my populateCells(summaryTable, column "A", categoryItems, true)
my formatCells(summaryTable, column "B", currency)
tell column 2
repeat with x from 2 to the count of cells
set theFormula to ("=SUMIFS(Amount,Category,A)")
set the value of cell x to theFormula
end repeat
end tell -- end telling column 2
end tell -- end telling summaryTable
-- Extreme hang starts on this table, specifically below where noted
set breakDownTable to make new table with properties {name:"Expenses By Month", column count:(count monthNames) + 1, row count:(count categoryItems) + 2, header column count:1, footer row count:1, header row count:1}
tell breakDownTable
set properties of row 1 to {background color:{moneyOutColor}}
my populateCells(breakDownTable, row 1, monthNames, true)
my populateCells(breakDownTable, column "A", categoryItems, true)
my formulateRow(breakDownTable, last row, "SUM")
set selection range to range "B2:M8"
set properties of selection range to {format:currency}
set value of last cell of column "A" to "Total"
--***** This is where the extreme hang begins
repeat with x from 1 to (count rows) - 2
repeat with y from 1 to count monthNames
copy incrementDates(y) of me to {theDayIndex, theMonthIndex, theYear, theDateString, monthLengthInDays}
set monthStart to theDateString
set monthEnd to theMonthIndex & "/" & monthLengthInDays & "/" & theYear as text
set theFormula to "=SUMIFS(Amount,Category,A,Date, \">=" & monthStart & "\",Date, \"<=" & monthEnd & "\")"
set value of cell (y + 1) of row (x + 1) to theFormula
end repeat
end repeat
--***** Extreme hang ends and script continues normally
add column after last column -- add a totals column after everything else is done
set totalsColumn to the last column
tell totalsColumn
set value of cell 1 to "Total"
my formulateColumn(breakDownTable, totalsColumn, "SUM")
end tell -- end telling totalsColumn
end tell -- end telling breakDownTable
end tell -- end telling sheet 2
make new sheet with properties {name:"Overview"}
tell sheet 3
delete every table
set cashFlowTable to make new table with properties {name:"Cashflow", column count:2, row count:(count monthNames) + 2, footer row count:1}
tell cashFlowTable
my populateCells(cashFlowTable, column "A", monthNames, true)
set value of last cell of column "A" to "Grand Total"
my formatCells(cashFlowTable, column "B", currency)
set value of cell "B1" to "Cashflow Totals"
set value of last cell to ("=SUM(B)")
tell column 2
repeat with x from 1 to count monthNames
set value of cell (x + 1) to ("=Money In::Money In Totals::Totals " & item x of monthNames & "−Money Out::Money Out Totals::Totals " & item x of monthNames)
end repeat
end tell -- end telling column 2
end tell -- end telling cashflow table
end tell -- end telling sheet 3
set active sheet to first sheet
end tell -- end telling document
end tell -- end telling Numbers
using terms from application "Numbers"
to populateCells(theTable, theDirection, theListToUse, usingHeaders)
tell theTable
set x to 1
if usingHeaders is true then
repeat with x from 1 to count theListToUse
set value of cell (x + 1) of theDirection to (item x of theListToUse)
end repeat
else
repeat with x from 1 to count theListToUse
set value of cell x of theDirection to (item x of theListToUse)
end repeat
end if
end tell
end populateCells
to formatCells(theTable, theDirection, theFormat)
tell theTable
set theRange to ¬
((name of cell 2 of theDirection) & ":" & ¬
(name of last cell of theDirection))
set selection range to range theRange
set properties of selection range to {format:theFormat}
end tell
end formatCells
to colorCells(theTable, theDirection, theColor)
tell theTable
set theRange to ¬
((name of cell 2 of theDirection) & ":" & ¬
(name of last cell of theDirection))
set selection range to range theRange
set properties of selection range to {background color:theColor}
end tell
end colorCells
to formulateColumn(theTable, theColumn, theType)
tell theTable
tell theColumn
repeat with i from 2 to the count of cells
set thisRow to the row of cell i
set rangeStart to the name of cell 2 of thisRow
set rangeEnd to the name of cell -2 of thisRow
set theFormula to ("=" & theType & "(" & rangeStart & ":" & rangeEnd & ")") as string
set value of cell i to theFormula
end repeat
end tell
end tell
end formulateColumn
to formulateRow(theTable, theRow, theType)
tell theTable
tell theRow
repeat with i from 2 to the count of cells
set thisColumn to the column of cell i
set rangeStart to the name of thisColumn
set rangeEnd to the name of thisColumn
set theFormula to ("=" & theType & "(" & rangeStart & ":" & rangeEnd & ")") as string
set value of cell i to theFormula
end repeat
end tell
end tell
end formulateRow
end using terms from
to incrementDates(tempMonth)
copy (current date) to tempDate
set day of tempDate to 1
set month of tempDate to tempMonth
set theDayName to weekday of tempDate
set theDayIndex to day of tempDate
set theMonth to month of tempDate
set theMonthIndex to theMonth as integer
set theMonthName to theMonth as string
set theYear to year of tempDate
set theDateString to short date string of tempDate
repeat with i from 1 to 32
set tempDate to tempDate + (1 * days)
if month of tempDate is not theMonth then
set monthLengthInDays to i
exit repeat
end if
end repeat
return {theDayIndex, theMonthIndex, theYear, theDateString, monthLengthInDays}
end incrementDates

After looking over your script, I've ran it and didn't experience the lag you're describing so that leaves the issue to your system or multiple test runs while writing the script.
Next as mentioned in the comments above, you can use the set command instead of copy in your incrementDates handler. You don't need a copy of (current date) each time your handler is invoked (12 times each call) so that could be changed to
to incrementDates(tempMonth)
set tempDate to (current date)
set day of tempDate to 1
set month of tempDate to tempMonth
set theDayName to weekday of tempDate
set theDayIndex to day of tempDate
set theMonth to month of tempDate
set theMonthIndex to theMonth as integer
set theMonthName to theMonth as string
set theYear to year of tempDate
set theDateString to short date string of tempDate
repeat with i from 1 to 32
set tempDate to tempDate + (1 * days)
if month of tempDate is not theMonth then
set monthLengthInDays to i
exit repeat
end if
end repeat
return {theDayIndex, theMonthIndex, theYear, theDateString, monthLengthInDays}
end incrementDates
from there you would still retrieve the values as you're currently doing.
Next you've also created a handler here where a handler isn't particularly needed.
to formatCells(theTable, theDirection, theFormat)
tell theTable
set theRange to ¬
((name of cell 2 of theDirection) & ":" & ¬
(name of last cell of theDirection))
set selection range to range theRange
set properties of selection range to {format:theFormat}
end tell
end formatCells
The above is the same as using
set properties of column named "Payment" to {format:currency}
The difference is negligible, but my general guide is don't reinvent the wheel. You're also not using a handler where a handler could be used when creating the totalsTable
to makeMonthlyTotalsTable(theTable, theColor)
tell theTable
set properties of row 1 to {background color:{theColor}}
my populateCells(totalsTable, column "A", monthNames, true)
set value of last cell of column "A" to "Grand Total"
set value of cell "B1" to "Totals"
set value of last cell to ("=SUM(B)")
tell column "B"
repeat with x from 1 to count monthNames -- loop and increment dates for the SUMIFS formula
copy incrementDates(x) of me to {theDayIndex, theMonthIndex, theYear, theDateString, monthLengthInDays}
set monthStart to theDateString
set monthEnd to theMonthIndex & "/" & monthLengthInDays & "/" & theYear as text
set the value of cell (x + 1) to ("=SUMIFS(Payment,Date, \">=" & monthStart & "\", Date, \"<=" & monthEnd & "\")")
end repeat
end tell -- end telling column B
end tell -- end telling totalsTable
end makeMonthlyTotalsTable
Again negligible difference and maybe opinion, but cleaner code if you plan on recreating that table in other sheets.
NOTE: I didn't test this handler, I just copied and pasted it from your script and changed the variable names to pass, but it should run fine as long as you set and declare the color name variables and switch monthNames to a property.
property monthNames : {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}

Related

Applescript | Extracting highest integer and create numbers from 0 to highest integer

I have a script returning the following results:
https://XY.com/shop/General-Mad-Dog-Mattis-For-PrN
https://XY.com/search?q=mad%20dog&p=29
https://XY.com/search?q=mad%20dog&p=26
Now i need to find the highest integer (in this case &p=29) and create new strings from https://XY.com/search?q=mad%20dog&p=0 up to the highest found integer in this case https://XY.com/search?q=mad%20dog&p=29
So far i managed to extract the URL's needed with the following code:
set AllUrls to {"https://XY.com/search?q=mad%20dog&p=26", "https://XY.com/search?q=mad%20dog&p=29", "https://XY.com/shop/General-Mad-Dog-Mattis-For-PrN"}
-- FILTER PAGING URLS
set PagingFilter to "&p="
set PagingUrls to {}
repeat with i from 1 to length of AllUrls
if item i of AllUrls contains PagingFilter then
set end of PagingUrls to item i of AllUrls
end if
end repeat
PagingUrls -- returns {"https://XY.com/search?q=mad%20dog&p=26", "https://XY.com/search?q=mad%20dog&p=29"}
And a small Script to extract the last 2 Digits from the URLs:
set alphabet to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
set myURLs to {"https://XY.com/search?q=mad%20dog&p=26", "https://XY.com/search?q=mad%20dog&p=29"}
set the text item delimiters of AppleScript to ¬
{space} & characters of the alphabet & {".", "_"}
set a to text items of myURLs as text
get last word of a --> returns "21"
set numlist to {}
repeat with i from 1 to count of words in a
set this_item to word i of a
try
set this_item to this_item as number
set the end of numlist to this_item
end try
end repeat
numlist -- returns {26, 29}
This is another approach.
It splits the URLs with text item delimiters by delimiter &p=. If the delimiter exists, get the integer (the right side of the delimiter) and save it as maxValue if the current value is higher than the previous value.
Then use a loop to create the list of page URLs
set AllUrls to {"https://XY.com/search?q=mad%20dog&p=26", "https://XY.com/search?q=mad%20dog&p=29", "https://XY.com/shop/General-Mad-Dog-Mattis-For-PrN"}
set maxValue to 0
set baseURL to ""
set TID to text item delimiters
set text item delimiters to "&p="
repeat with anURL in AllUrls
set textItems to text items of anURL
if (count textItems) is 2 then
set currentValue to item 2 of textItems as integer
if currentValue > maxValue then set maxValue to currentValue
set baseURL to item 1 of textItems & "&p="
end if
end repeat
set text item delimiters to TID
set pageURLs to {}
repeat with i from 0 to maxValue
set end of pageURLs to baseURL & i
end repeat

applescript to create multiple sequentially numbered folders with a specific prefix

I would like to create an applescript that will create multiple folders with the same root name but the numbers change? or at least a repeating folder creation script until the person has enough folders. So something that makes folders like this: JOYR-15-0035-00, JOYR-15-0036-00, JOYR-15-0037-00 and so on. Is that at all possible? I am just learning this. I am normally a graphic designer but I feel like I can get a lot from applescript.
Currently I just have this basic script:
tell application "Finder"
set KDID to text returned of (display dialog "Enter the KDID ID:" default answer "JOYR-")
set loc to choose folder "Choose Parent Folder Location"
set newfoldername to {name:KDID}
set newfo to make new folder at loc with properties {name:KDID}
reveal newfo
end tell
Try this, it assumes that the KDID is just the number 15 in the example, the syntax is always JOYR-<KDID>-<consecutive number>-00 and the leading JOYR as well as the trailing double zero don't change.
The script asks for the parent folder, the KDID and the number of sequential folders. Then it checks the parent folder for the greatest existing number (the 0035 part) and creates folders starting with the greatest number plus 1 or – if no existing folders are found – with 1. The number has always four digits.
property letterPrefix : "JOYR"
property KDID : "15"
property parentFolder : missing value
set parentFolder to choose folder "Choose Parent Folder Location"
tell application "Finder"
activate
set KDID to text returned of (display dialog "Enter the KDID ID:" default answer "15")
repeat
set howManyFolders to text returned of (display dialog "Enter the Number of Folders to create:" default answer "1")
try
set howManyFolders to howManyFolders as integer
if howManyFolders < 1 then error
exit repeat
on error
display dialog "Please enter an integer value greater than 0" default answer "1"
end try
end repeat
set currentNumber to my getGreatestFolderNumber()
repeat howManyFolders times
set folderName to letterPrefix & "-" & KDID & "-" & my pad(currentNumber) & "-00"
make new folder at parentFolder with properties {name:folderName}
set currentNumber to currentNumber + 1
end repeat
open parentFolder
end tell
on getGreatestFolderNumber()
tell application "Finder"
set {ASTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "-"}
try
set folderNames to name of folders of parentFolder whose name starts with (letterPrefix & "-" & KDID & "-")
set maxNumber to 0
repeat with aName in folderNames
set curNumber to (text item 3 of aName) as integer
if curNumber > maxNumber then set maxNumber to curNumber
end repeat
set AppleScript's text item delimiters to ASTID
return maxNumber + 1
on error
set AppleScript's text item delimiters to ASTID
return 1
end try
end tell
end getGreatestFolderNumber
on pad(v)
return text -4 thru -1 of ("000" & v)
end pad

Find and replace in Excel 2011 using Applescript

I was wondering if anyone could help me. I'm trying to find and replace blank spaces in an excel workbook. I want it to search the current sheet I'm on in a workbook, find all instances of "" and replace it with " ".
Does anyone happen to know how to do this?
With Applescript:
searchAndReplaceTextInCells("hello", "world")
on searchAndReplaceTextInCells(search_str, replace_str)
tell application "Microsoft Excel"
set search_range to range "A:Z"
set all_found_ranges to {} -- store for the ranges, to manipulate after searching
set found_range to ""
set counter to 0
try
set found_range to find search_range what search_str with match case
on error
log ("No matches found")
end try
if (found_range is not "") then
set first_cell_address to (get address of the cells of found_range) -- we use this to break our loop
repeat while true
set counter to counter + 1
copy found_range to end of all_found_ranges
-- Now look for next result
set found_range to find next search_range after found_range
set cell_address to (get address of the cells of found_range)
if (cell_address = first_cell_address) then
-- have looped around so we are finished!
exit repeat
end if
end repeat
end if
-- walk all the ranges found and do the string replacing
repeat with r in all_found_ranges
set value of r to my replace_chars(the value of r, search_str, replace_str)
end repeat
log ("found and replaced " & counter & " items")
end tell
end searchAndReplaceTextInCells
on replace_chars(this_text, search_string, replacement_string)
set my text item delimiters to the search_string
set the item_list to every text item of this_text
set my text item delimiters to the replacement_string
set this_text to the item_list as string
set my text item delimiters to ""
return this_text
end replace_chars
How about Command + F, and hit the Replace button to give you this:
Have you tried the following:
replace range targetRange what searchStr replacement replaceStr
This should be rather straight forward replacement statement.

Applescript timed out in iTunes

I wrote a simple applescript to automatically add files into iTunes and fill the metadata. When I run it directly from the editor it works but running it from iTunes and I will get "AppleEvent Timed Out".
Here's the code:
set mainFolder to choose folder
tell application "Finder"
-- Loop through all shows
set shows to every folder of mainFolder
repeat with show from 1 to count of shows
-- Set Show Name
set showName to name of item show of shows
-- Set Artist
display dialog "Who is the artist for " & showName & "?" default answer showName
set showArtist to the text returned of the result
-- Set Genre
display dialog "What is the genre for " & showName & "?" default answer ""
set showGenre to the text returned of the result
-- Loop through all season
set seasons to every folder in item show of shows
repeat with season from 1 to count of seasons
set seasonName to name of item season of seasons
-- Set Season Number
set seasonNumber to text 1 thru ((offset of "-" in seasonName) - 2) of seasonName as integer
-- Set Year
display dialog "What year was Season " & seasonNumber & " of " & showName & " in?" default answer "2012"
set showYear to the text returned of the result
-- Set Season Name
set seasonName to text ((offset of "-" in seasonName) + 2) thru ((offset of "." in seasonName) - 1) of seasonName as text
-- Set Total Episodes in Season
set totalEpisodes to count of every file in item season of seasons
-- Loop through all episodes
set episodes to every file in item season of seasons
repeat with episode from 1 to count of episodes
set episodeName to name of item episode of episodes
-- Set Episode Number
set episodeNumber to text 1 thru ((offset of "-" in episodeName) - 2) of episodeName as integer
-- Set Episode Name
set episodeName to text ((offset of "-" in episodeName) + 2) thru ((offset of "." in episodeName) - 1) of episodeName as text
tell application "iTunes"
set newAddition to (add (item episode of episodes as alias))
tell newAddition
set video kind to TV show
set name to episodeName
set album to seasonName
set track number to episodeNumber
set track count to totalEpisodes
set disc number to "1"
set disc count to "1"
set show to showName
set season number to seasonNumber
set episode number to episodeNumber
-- Manual Entries
set artist to showArtist
set genre to showGenre
set year to showYear
-- Change episode ID based on season and episode number
if (seasonNumber < 10) then
if (episodeNumber < 10) then
set episode ID to ("S0" & seasonNumber as text) & "E0" & episodeNumber as text
else
set episode ID to ("S0" & seasonNumber as text) & "E" & episodeNumber as text
end if
else
if (episodeNumber < 10) then
set episode ID to ("S" & seasonNumber as text) & "E0" & episodeNumber as text
else
set episode ID to ("S" & seasonNumber as text) & "E" & episodeNumber as text
end if
end if
end tell -- End newAddition
end tell -- End iTunes
end repeat -- End Episode Repeat
end repeat -- End Season Repeat
end repeat -- End Show Repeat
end tell -- End Finder Repeat
the code itself seems sound assuming you don't have any errors when calculating the offsets and different components of the file name. However I can see 2 possible sources of errors that may fix your problem.
First, you have your iTunes tell block of code inside your Finder tell block of code. Essentially you are telling the Finder to tell iTunes to do something. That is a source of possible errors. You should separate your tell blocks from each other. For example you have this...
tell application "Finder"
-- do something
tell application "iTunes"
-- do something
end tell
end tell
When you should have it like this...
tell application "Finder"
-- do something
end tell
tell application "iTunes"
-- do something
end tell
Second, you have a mistake in your "episode id" code with the parenthesis. For example this...
("S0" & seasonNumber as text)
Should be this...
"S0" & (seasonNumber as text)
As such I have separated out the iTunes stuff into a subroutine and fixed the parenthesis. Note that I haven't tested this code. I think I passed all of the proper variables to the subroutine but I can't be certain. I hope this helps.
set mainFolder to choose folder
tell application "Finder"
-- Loop through all shows
set shows to every folder of mainFolder
repeat with show from 1 to count of shows
-- Set Show Name
set showName to name of item show of shows
-- Set Artist
display dialog "Who is the artist for " & showName & "?" default answer showName
set showArtist to the text returned of the result
-- Set Genre
display dialog "What is the genre for " & showName & "?" default answer ""
set showGenre to the text returned of the result
-- Loop through all season
set seasons to every folder in item show of shows
repeat with season from 1 to count of seasons
set seasonName to name of item season of seasons
-- Set Season Number
set seasonNumber to text 1 thru ((offset of "-" in seasonName) - 2) of seasonName as integer
-- Set Year
display dialog "What year was Season " & seasonNumber & " of " & showName & " in?" default answer "2012"
set showYear to the text returned of the result
-- Set Season Name
set seasonName to text ((offset of "-" in seasonName) + 2) thru ((offset of "." in seasonName) - 1) of seasonName as text
-- Set Total Episodes in Season
set totalEpisodes to count of every file in item season of seasons
-- Loop through all episodes
set episodes to every file in item season of seasons
repeat with episode from 1 to count of episodes
set episodeName to name of item episode of episodes
-- Set Episode Number
set episodeNumber to text 1 thru ((offset of "-" in episodeName) - 2) of episodeName as integer
-- Set Episode Name
set episodeName to text ((offset of "-" in episodeName) + 2) thru ((offset of "." in episodeName) - 1) of episodeName as text
my addEpisodeToItunes((item episode of episodes) as alias, seasonName, seasonNumber, episodeName, episodeNumber, totalEpisodes, showName, showArtist, showGenre, showYear)
end repeat -- End Episode Repeat
end repeat -- End Season Repeat
end repeat -- End Show Repeat
end tell -- End Finder Repeat
on addEpisodeToItunes(theEpisode, seasonName, seasonNumber, episodeName, episodeNumber, totalEpisodes, showName, showArtist, showGenre, showYear)
tell application "iTunes"
set newAddition to add theEpisode
tell newAddition
set video kind to TV show
set name to episodeName
set album to seasonName
set track number to episodeNumber
set track count to totalEpisodes
set disc number to "1"
set disc count to "1"
set show to showName
set season number to seasonNumber
set episode number to episodeNumber
-- Manual Entries
set artist to showArtist
set genre to showGenre
set year to showYear
-- Change episode ID based on season and episode number
if (seasonNumber < 10) then
if (episodeNumber < 10) then
set episode ID to "S0" & (seasonNumber as text) & "E0" & (episodeNumber as text)
else
set episode ID to "S0" & (seasonNumber as text) & "E" & (episodeNumber as text)
end if
else
if (episodeNumber < 10) then
set episode ID to "S" & (seasonNumber as text) & "E0" & (episodeNumber as text)
else
set episode ID to "S" & (seasonNumber as text) & "E" & (episodeNumber as text)
end if
end if
end tell -- End newAddition
end tell -- End iTunes
end addEpisodeToItunes
Here is how I solved it:
Save as an app instead of a script.
I got the solution from here:
http://forums.ilounge.com/applescripts-itunes-mac/245120-need-help-add-tracks-files-via-applescript.html
I have no clue why it's doing that, I've tried using try-catch, timeout... still didn't work. It works as an app though?!

How to loop through all rows in Excel using Applescript?

I'm trying to loop through all rows in Excel and run some command on each row, but I can't figure out how!
I tried initially doing that in rb-appscript (the Ruby wrapper for AppleScript) but decided that I'd be better off trying to get it working first in Applescript before adding another DSL. Any tips? (the rb-appscript version would be nice, too, though not required).
Thanks!
The coordinates of a range is a string that you can create dynamically. The simplest way to loop through your rows would be something like this:
repeat with thisRow from 1 to 10
tell application "Microsoft Excel"
set theRange to "A:" & thisRow & "Z:" & thisRow
set theValue to (get value of range theRange) as list
-- do something with the row's data
end tell
end repeat
Update per comments: To get the number of rows needing calculation, I wrote a subroutine ages ago to help with this. Be sure you have some kind of "key" column that is consistently populated (in other words, there are no skipped cells). This currently takes into account a header row since all of my spreadsheets have them:
on GetItemCount(KeyColumn)
set RowNumber to 1
set theText to "cSyoyodylg" -- dummy value
tell application "Microsoft Excel"
repeat until theText is ""
set RowNumber to RowNumber + 1
set theRange to KeyColumn & RowNumber & ":" & KeyColumn & RowNumber
set dataRange to range theRange of sheet 1
set theText to (get value of range theRange)
end repeat
end tell
set rowCount to RowNumber - 1
return rowCount
end GetItemCount
To use simply do this:
set lastRow to GetItemCount("A") of me
repeat with thisRow from 2 to lastRow + 1
-- go attack Excel
end repeat

Resources