Open files from a folder that contains subfolders

I have created this script to search for files that exist within a folder on my desktop. (sorry about the odd drive names, and folder path). I am not good at scripting”so my script is probably very ugly.

But what I have below works fine, until I realized that the the “SpecAds” folder will contain subfolders.

Can anyone help me set this up, so it searches any and all of the subfolders within the SpecAds folder?

I hope this can be done without having to list all the subfolders names?

tell application "Finder"
	set thePath to folder "Illustrations:Users:admin:Desktop:SpecAds"
	
end tell
set myDialog to display dialog "Enter Spec Number" default answer "10000" buttons {"Cancel", "OK"} default button 2

set userReply to text returned of myDialog

tell application "Finder"
	try
		set theNumber to (count of (every file in thePath whose name is equal to "SPEC." & userReply))
		set theNumber2 to (count of (every file in thePath whose name is equal to userReply))
		if theNumber is greater than 0 then open (every file in thePath whose name is equal to "SPEC." & userReply) using application file id "CARO"
		if theNumber2 is greater than 0 then open (every file in thePath whose name is equal to userReply) using application file id "CARO"
		if theNumber is less than 1 and theNumber2 is less than 1 then display dialog "Couldn't find " & userReply buttons {"Cancel"} default button 1
		
	end try
end tell

use

  set theNumber to count of (every file of entire contents in thePath whose name is equal to "SPEC." & userReply)

instead of

 set theNumber to (count of (every file in thePath whose name is equal to "SPEC." & userReply))

the parenthesis before count is not necessary

I’d rewrite the script to avoid doing the 'every file of … search four times - maybe like this:

tell application "Finder"
   try
       set theFiles to (every file of (entire contents of thePath) whose name is equal to ("SPEC." & userReply) or name is equal to userReply)
       if (count of theFiles) > 0 then 
              repeat with thisFile in theFiles
                   open thisFile using application file id "CARO"
              end repeat
       else
              display dialog "Couldn't find " & userReply buttons {"Cancel"} default button 1
       end if
   end try
end tell

D.

I am so thankful for your responses. You set this up so cleanly and made this look so easy. I was stressing over this, trying my own repeat functions but failing miserably.

This particular line below says and does a lot :slight_smile:
if (count of theFiles) > 0 then

Thanks again for both of your great help.

-Jeff