The Dir$() function and searching files under a directory

A

andywirtanen

Hello,

I was wondering if it was possible to search filenames under a
directory using Dir$() or if I would have to use If and Instr
statements to search individual filenames.

In other words, I have a directory, in which there are a bunch of files
with filenames that all begin with the same pattern. I want to grab
only those
files and not have to search the entire directory.

Here's what I tried:

While Dir$("C:\theDirectory\" & theSearchTerm & "*.*") <> ""
' Do stuff
Wend

Thanks,

Andy
 
K

Karl E. Peterson

Nevermind, that works.

Be very careful with that "Do stuff" part, though! Most folks would agree (for a
variety of hard-earned knocks) that the best approach is to first build an array of
filenames you want to operate on, then iterate the array.

Also, looking at what you're doing, that's gonna cause issues, anyway. Cleaning it
up a bit, you'd really want something more like:

Dim f As String

f = Dir$("C:\theDirectory\" & theSearchTerm & "*.*")
Do While Len(f)
' Stuff
f = Dir$()
Loop

Later... Karl
 
J

Jean-Guy Marcil

Karl E. Peterson was telling us:
Karl E. Peterson nous racontait que :
Be very careful with that "Do stuff" part, though! Most folks would
agree (for a variety of hard-earned knocks) that the best approach is
to first build an array of filenames you want to operate on, then
iterate the array.

Yeah, been there.
I once had a "do stuff" that ended up processing each file twice... Not
what I wanted!

--
Salut!
_______________________________________
Jean-Guy Marcil - Word MVP
(e-mail address removed)
Word MVP site: http://www.word.mvps.org
 
J

Jezebel

The other trap is is trying to use Dir$() recursively, to process the
sub-folders. oh dear ...
 
J

Jonathan West

Hi Andy,

For the various reason referred to in this thread, you might want to
consider not using Dir() at all for this. You might want to take a look at
the following article for an alternative approach

http://vbnet.mvps.org/code/fileapi/recursivefiles_minimal.htm

The code is VB6 rather than VBA, but will only require minimal modification
to work in a VBA UserForm instead of a VBA form.

--
Regards
Jonathan West - Word MVP
www.intelligentdocuments.co.uk
Please reply to the newsgroup
Keep your VBA code safe, sign the ClassicVB petition www.classicvb.org
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top