Question

I need to check if a file exists within a directory. The two options I thought of are using a regex (vbscript.regexp) to determine if the file is present. The other option being to use the FileSystemObject's FileExists method.

The cons of using the regex implies that I will need to loop through every file in the directory and test the regex against each filename. Secondly, a regex approach may be harder to maintain (the regex) in the future. However, I need to test two regex's since there may be a different version of the same file. For one of the files, there is a description part of the filename which changes frequently(ok, that's a lie - it changes on some random cycle), so using a regex will assist in matching the files regardless of this part = more robust code.

Using FileExists, I can test for both files simultaneously and depending on the boolean value returned for each check, processing can continue. The related downside for using FileExists is that wildcard matching is not supported, so when considering the filename with a description, this will always need to be updated to reflect the new description = more maintenance headaches. However, it is simpler to grasp and easier to change.

Format of filenames:

Data_Sheet_<yyyymmdd>_D.xlsx // the normal file
Data_Sheet_<yyyymmdd>_D_<some description>.xlsx // the alternate file

The <yyyymmdd> part of the filename will be determined by the current folder the file is located in.

The question: Would it be better to use a regex or a simple FileExists to find files?

I will using the either of the above methods within an Excel vba macro.

Was it helpful?

Solution

Have you looked at Dir() ? You can pass it wildcards Like my*file.pd? Perhaps it might be a way to compromise. Sure you wouldn't get the full power of a regex, but you could limit your files and then actually test to see what exists.

Personally I would use FileExists() rather than looping over a directory and testing every file. If the directory got huge than your loop could take forever. Though if you use Dir() you could potentially limit the number of files you need to iterate over. Plus FileExists() is exactly one line/statement and cleaner... though then you have to make sure the Scripting Runtime is included in your project

http://techonthenet.com/excel/formulas/dir.php http://www.blueclaw-db.com/listbox-directory.htm http://www.hobbub.com/vba-vb-vsto/iterating-over-a-directory-with-a-dir-loop-loop-through-directory-vb/

Second and third links have better examples of iterating over the directory.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top