How to check if no subfolder exists?

I have a script that finds the newest folder in a list of subfolders (based on creation date).

set folderSelected to choose folder “Select Destination”

tell application “Finder”

set ListOf_SubFolders to every folder of folderSelected as string
display dialog "Subfolders are " & ListOf_SubFolders

set sortedlist to sort (get folders of folderSelected) by creation date
set DestFolder to first item of sortedlist as string

display dialog DestFolder

end tell

How can I add error checking such that if there are no subfolders, the script instead creates one? (i.e. something along the lines of a null test).

Model: iMac
Browser: Safari 525.13
Operating System: Mac OS X (10.5)

Is this along the lines of what you are looking for?

set folderSelected to choose folder "Select Destination"

tell application "Finder"
	
	set ListOf_SubFolders to every folder of folderSelected as string
	if ListOf_SubFolders is not "" then
		display dialog "Subfolders are " & ListOf_SubFolders
		
		set sortedlist to sort (get folders of folderSelected) by creation date
		set DestFolder to first item of sortedlist as string
		
		display dialog DestFolder
	else
		make new folder at folder folderSelected with properties {name:"Untitled"}
	end if
end tell

Thanks for this. I had coded a longer winded workaround using an “on error” statement (-1700 is returned if no subfolders exist), but your code is a lot neater.

I have one further question. If subfolders do already exist, then they will be named Folder 1, Folder 2, Folder 3 etc. If there are any subfolders, I want to set a variable to be the digit(s) at the end of the folder name of the most recently created folder. I can’t just get the folder name, and then trim everything except the folder digits, as there are no leading zeros in the folder names, so I don’t know how many digits to keep.

Therefore, is it possible to set a variable to equal the no. of items in a list? This will always correspond to the digits of the most recently created folder (in my case), as I created them in order with no gaps in the folder numbering - Folder 1, Folder 2, folder 3 etc.

sure thing! To just get a count is as easy as

set folderCount to count sortedlist

If the folder names follow a reliable pattern though such as always having the same name except for the number or no spaces except before the number then it shouldn’t be too hard to strip the number out for identification purposes.