Full Version: Select File With Highest Suffix
UtterAccess Discussion Forums > Microsoft® Office > Microsoft Excel
kespicer
In VBA, I want to use DIR to go thru a folder and return the file which has the highest alphabetical suffix, with "no suffix" being the lowest value.

FILES:

111.doc
222.doc
222A.doc
333.doc
333A.doc
333B.doc

For the examples above, it would return 111.doc (which has no suffix), 222A.doc and 333B.doc.

How can this be done?
doctor9
This isn't the most memory-efficient logic, but it should work:

1. Set up an array of strings to store all of your filenames, called "strFileName()" for example.
2. Set up an array of strings to store a list of filenames that share the same suffix. Call it strSelectedFiles().
3. Set up an array of strings to be returned as the list of files that have the highest alphabetical suffix, called strReturnedFilenames().
***Find the "no suffix" filenames:
3. Using Left(Right(strFileName(x),5),1) as a way to grab the last character of the filename (assuming all files have a three-character extension), you can determine whether the "suffix" is a letter or a number.
4. If it's a number, add it to the strSelectedFiles() array.
5. Once all of the "no suffix" filenames are in the strSelectedFiles() array, sort them alphabetically, and add the first one in the list to the strReturnedFilenames() array.
6. Clear the strSelectedFiles() array.
***Find the first filename with each lettered suffix:
7. Loop from A to Z
8. Using Left(Right(strFileName(x),5),1) as a way to grab the last character of the filename, determine whether the suffix matches the current letter in the loop.
9. If it's a match, add the filename to the strSelectedFiles() array.
10. Once all of the files have been evaluated, sort the strSelectedFiles() array alphabetically, and add the first one in the list to the strReturnedFilenames() array.
11. End of loop
12. Return the list of filenames in strReturnedFilenames().

Of course, it's not necessary for the strSelectedFiles() array and the strReturnedFilenames() array to contain redundant string data. Instead, you can store an integer that represents the index of the filename in the strFilename() array.

Hope this helps,

Dennis
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.