Check file exist vba

Av8tordude

Well-known Member
Joined
Oct 13, 2007
Messages
902
I'm using MKDir to create a file in a folder. When creating a file, the file name is saved with a random generated 16-digits Alpha-Numeric (i.e. DS1O-Q7LN-X7MP-EJA8) name. The code below checks for a specific file, however How can i check if there is a 16-digits Alpha-Numeric file exist?

Code:
Function FileExists(FilePath As String) As Boolean
Dim TestStr As String
    TestStr = ""
    On Error Resume Next
    TestStr = Dir(FilePath)
    On Error GoTo 0
    If TestStr = "" Then
        FileExists = False
    Else
        FileExists = True
    End If
End Function
 

Some videos you may like

Excel Facts

Ambidextrous Undo
Undo last command with Ctrl+Z or Alt+Backspace. If you use the Undo icon in the QAT, open the drop-down arrow to undo up to 100 steps.

AlphaFrog

MrExcel MVP
Joined
Sep 2, 2009
Messages
16,271
You want to check if any 16 character filename exists in a given folder?

Code:
[color=darkblue]Function[/color] FileExists(FilePath [color=darkblue]As[/color] [color=darkblue]String[/color]) [color=darkblue]As[/color] [color=darkblue]Boolean[/color]
    
    [color=darkblue]If[/color] Right(FilePath, 1) <> "\" [color=darkblue]Then[/color] FilePath = FilePath & "\"
    
    FileExists = Len(Dir(FilePath & "????-????-????-????.*")) > 0
    
[color=darkblue]End[/color] [color=darkblue]Function[/color]
 

Av8tordude

Well-known Member
Joined
Oct 13, 2007
Messages
902
If a file exist in the described format above, How can I insert the file name in cell? I tried the code below, but it not entering the correct file name.

Code:
Range("A1") = Len((Dir(OPath) & "????-????-????-????.*"))
 
Last edited:

Subscribe on YouTube

Watch MrExcel Video

Forum statistics

Threads
1,105,855
Messages
5,507,733
Members
408,647
Latest member
Nicho la zido

This Week's Hot Topics

Top