Add sequential numbers to identical file names

I am writing a script to save email messages I send as word documents. The file name I use is the subject of the email message. Often the subject remains the same as a result when I save the document it will overwrite an existing file. I have used the exists command in finder which will check if a file exists and I have then added 1 to the file name. My problem occurs if there are more than two messages with the same subject. This is what I have for making the document.

on makeADoc(ccNames, cc_, sent_, subject_, content_)
tell application “Microsoft Word”
set newDoc to make document
insert text “To :” & ccNames & return at end of text object of newDoc
insert text “CC :” & cc_ & return at end of text object of newDoc
insert text “Date Sent :” & sent_ & return & return at end of text object of newDoc
insert text “Subject :” & subject_ & return & return at end of text object of newDoc
insert text content_ at end of text object of newDoc --Adds Message text
tell application “Finder”
set checkFile to folderpath_ & subject_ as string
if checkFile exists then --Check if proposed file name already exists
set subject_ to subject_ & " 1" --adds number to name
end if
end tell
save as newDoc file name folderpath_ & subject_ --file_ Saves Document with file name of the subject in email message
close every document
end tell
end makeADoc

The result is if I have three messages with the same subject, the first will save OK the second will save with 1 appended to the subject the third will see that the first exists and then over write the second… I had thought of running a loop with a number added to each subject increasing by 1 and checking the result but that seems very cumbersome can anyone suggest an alternative.

Thanks

Mitch

Model: iMac MacBookPro
AppleScript: 2.1.2
Browser: Safari 533.16
Operating System: Mac OS X (10.6)

hi,

you could try something like this:



global counter
set counter to 0
set NewDocName to my checkAlias("Macintosh HD:Users:hans:Desktop:Protokoll29_09_10.doc") --your savepath

on checkAlias(PathtoFile)
	
	repeat
		try
			alias PathtoFile --does the file allready exist?
		on error
			return PathtoFile --no, then fine name ...
			exit repeat --finished here
		end try
		set counter to counter + 1 --else: set the counter
		set PathtoFile to PathtoFile & counter as text --add counter as text to PathtoFile
		my checkAlias(PathtoFile) --start over
	end repeat
end checkAlias

Hans: Thank you very much I am new to applescript and you showed me two things I did not know you could do 1 exit repeat and 2 loop back on the handler. I feel sure I will be able to make this work thanks again.

Mitch