Using wildcard in file name

F

franky

I'm trying to create a function to see if a file exists in a directory.
Sometimes, I only have the begining part of a file name and need to use a
wildcard for the rest. How would I do this?

The following function works (got off web) if the file name is explicitly
there but returns "false" if I attempt to put a wildcard in any part of the
argument.

ie: "c:\test*.txt"

Function DoesFileExist(strFileSpec As String) As Boolean
' Return True if file specified in the
' strFilespec argument exists.
' Return False if strFileSpec is not a valid
' file or if strFileSpec is a directory.
Const INVALID_ARGUMENT As Long = 53
On Error GoTo DoesfileExist_Err
If (GetAttr(strFileSpec) And vbDirectory) <> vbDirectory Then
DoesFileExist = CBool(Len(Dir(strFileSpec)) > 0)
Else
DoesFileExist = False
End If
DoesfileExist_End:
Exit Function
DoesfileExist_Err:
DoesFileExist = False
Resume DoesfileExist_End
End Function


Thanks in advance!
 
D

Douglas J. Steele

The GetAttr function doesn't support wildcards.

You might be able to use something like the following untested air-code

Function DoesFileExist(strFileSpec As String) As Boolean
' Return True if file specified in the
' strFilespec argument exists.
' Return False if strFileSpec is not a valid
' file or if strFileSpec is a directory.
On Error GoTo DoesfileExist_Err

Dim strFile As String

strFile = Dir(strFileSpec)
If Len(strFileSpec) > 0 Then
DoesFileExist = (GetAttr(strFile) And vbDirectory) <> vbDirectory
Else
DoesFileExist = False
End If

DoesfileExist_End:
Exit Function
DoesfileExist_Err:
DoesFileExist = False
Resume DoesfileExist_End
End Function

although I don't think it'll be 100% accurate.

However, the idea of using a wildcard to check for existence of a file
doesn't really make sense to me.
 
D

Douglas J. Steele

John Nurick said:
AFAIK you only get directories if you specify
Dir(strFileSpec, vbDirectory)

Yeah, I guess you're right.

Len(Dir("C:\Windows") is 0, while Len(Dir("C:\Windows\") isn't.
 

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