Creating a numbered variable that alters in a repeat loop

Hey All!!

Happy New Year!!! Another decade gone - scary!!!

Anyway, my question is - is it possible to somehow create a variable name that will alter every time it goes around a repeat loop??

i.e. if the variable is x1 the first time, it would be x2 the second time, x3 the third time etc.

I had something in mind like this, but it does not like this…


set i to 1
repeat until i is 10
set ("x" & i) to value of cell ("B" & i) as integer
set i to i + 1
end repeat


Any suggestions…Thanks in advance…

DDHawk

As far as I know, AppleScript can’t convert a text string to a variable. It’ll keep telling you access not allowed because the compiler thinks you want X4 itself to become 93.

I’d use a list.

tell application "Microsoft Excel"
	set mySize to 10
	set myCell to range "B1"
	
	set myList to {}
	
	repeat with i from 1 to mySize
		copy (value of (get offset myCell row offset (i - 1)) as integer) to end of myList
	end repeat

	myList
end tell

The Excel details of how you loop through the range would depend on what range you are given.

But in general, a list with 10 elements is easier to work with than the 10 variables x1,x2,x3,…,x10.

Hi,

i guess it’s a Record you’re asking for …

tell application "Microsoft Excel"
	set mySize to 10
	set myCell to range "B1"
	
	set myList to {}
	
	set theString to ""
	set counter to 0
	repeat with i from 1 to mySize
		
		set counter to counter + 1
		
		set theItem to (value of (get offset myCell row offset (i - 1) as integer))
		
		if counter is equal to mySize then
			set theRecord to ("variable_" & counter as text) & ":" & "\"" & theItem & "\""
		else
			set theRecord to ("variable_" & counter as text) & ":" & "\"" & theItem & "\", "
		end if
		
		set theString to theString & theRecord
		
	end repeat
	
end tell

set theRecordList to run script "{" & theString & "}"

… but I also guess that you won’t need one, cause handling a list is much easier …

You can do what you want. It takes an advanced technique to accomplish though… we use objective-c. An applescript record is a “dictionary” in objective-c. As such we use the “call method” technique to create the objective-c dictionary so we can create the variable names like you want. Then we put that dictionary in an applescript list so you can use it normally…

set myArray to {}

tell application "Automator Runner"
	repeat with i from 1 to 9
		set theKey to ("x" & i) as text
		set thisDict to call method "dictionaryWithObject:forKey:" of class "NSDictionary" with parameters {i, theKey}
		set myArray to myArray & thisDict
	end repeat
end tell

return myArray

Dear All,

Thank you very much for your replies. I will try to incorporate the ideas into my program.

Kindest regards,

DDHawk