Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


Finding a file

Posted on 2000-03-27
Medium Priority
Last Modified: 2010-05-02

I have to find if an exe file exists using Visual Basic 6. The file can be in any path or drive.I should check if the file is present without specifying the path explicitly.This is similar to the Find file option in windows. How do i write VB code for this.I have written the code to identify the drives present.


Private Sub Command1_Click()
Dim myfile, mypath, myname, nextPath
Set fso = CreateObject("Scripting.FileSystemObject")
Set dc = fso.Drives
For Each d In dc
    s = d.DriveLetter
    If s <> "A" Then
    mypath = "" & s & ":\Program Files\Microsoft Office\Office\"
       myname = Dir(mypath)
    Do While myname <> ""
    'If myname <> "." & myname <> ".." Then
    'If (GetAttr(mypath & myname) And vbDirectory) = vbDirectory Then
            'Debug.Print myname
            If myname = "EXCEL.EXE" Then MsgBox myname & " - Excel present"
            If myname = "WINWORD.EXE" Then MsgBox myname & " - Word Present"
    'End If
    'End If
   myname = Dir
   End If
End Sub
Question by:Brindha
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
  • 2
  • +4
LVL 28

Expert Comment

ID: 2663019
very good example here for download:

Expert Comment

ID: 2663176
This should work

Option Explicit
    Dim fileCo As Integer
    Dim thisPath As String
    Dim filecount As Single
    Dim filelentot As Single

Private Sub FindFileBtn_Click()
    Dim inspectfilename, findperiod, findstar, i
    Dim driveselected As String, msg As String
    Dir2.Path = App.Path
   filelentot = 0: filecount = 0

    list1.Clear     'clear the listbox
    File1.Pattern = "execl.exe"  'gives the program the pattern to look for
    driveselected = Left$(Drive1.Drive, 2) & "\" 'tells which drive is selected
    Drive1.Drive = "c:\"
    Dir1.Path = Drive1.Drive
    File1.Path = Dir1.Path
    ChDir "\"   'starts at the root directory
    GetFileList driveselected    'makes the call to the getfilelist proc
 'I have returned from the get file list procedure

    If filelentot > 0 Then '
        status = "Size of files is - " & Format(filelentot, "###,###,###")
        status = status & " Bytes" & "    File Count - " & Format(filecount, "###,###")
        Me.status.Visible = False
    End If

MsgBox "File not present", vbOKOnly
End Sub

Private Sub GetFileList(ByVal p$)

Dim T$, i As Integer

If Dir1.ListCount > 0 Then
  For i = 0 To Dir1.ListCount - 1
    T$ = Dir1.List(i)
    GetFileList (T$)
    Dir1.Path = p$
  '  Me.status = p$
  '  Me.status.Refresh
End If

End Sub
LVL 14

Accepted Solution

wsh2 earned 150 total points
ID: 2663254
If Excel and Word are what you are looking for.. how about finding them through file association.. <smile>.

Syntax for use:

Dim strCommand as String
Dim StrExtension as String

strExtension = "DOC"

strCommand = xFindExecutable(strExtension)
If strCommand = "" _
  msgbox("NOT FOUND")
End If

<----- Code Begin ----->

Private Declare Function FindExecutable Lib "shell32.dll" Alias "FindExecutableA" _
  (ByVal lpFile As String, _
  ByVal lpDirectory As String, _
  ByVal lpResult As String) _
  As Long

Public Function xFindExecutable _
(ByVal strExtension As String) _
As String

  ' Build a sample test file
  Dim strFileSample As String
  strFileSample = "c:\tempwork\~test." & strExtension ' Change Path to whatever you like
  If Dir(strFileSample) = "" _
    Dim intFileNumber As Integer
    intFileNumber = FreeFile
    Open strFileSample For Binary Access Write As intFileNumber
    Put intFileNumber, , "x"
    Close intFileNumber
  End If

  ' Get Executable string
  Dim strProgram As String
  Dim lngReturn As Long
  strProgram = Space(255)
  lngReturn = FindExecutable(strFileSample, "", strProgram)
  If lngReturn > 32 _
    xFindExecutable = Left$(strProgram, InStr(1, strProgram, Chr(0)) - 1)
    xFindExecutable = ""
  End If
  On Error Resume Next
  Kill strFileSample
  On Error GoTo 0
End Function

<----- Code End ----->
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

LVL 10

Expert Comment

ID: 2663263
LVL 14

Expert Comment

ID: 2663295
How can you propose that as a definitive answer?.. First of all the questioner is using FSO for accessing the tree structure.. Second.. you fail to mention that Drive, Directory and File controls have got to be added to the program.. Third.. there is are APIs that will achieve the same thing you are doing only faster.

Please let the questioner decide which is the best comment.. not force your answer upon them.. <smile>.

Unless Riduce's answer is conclusive for you, REJECT his answer and allow others to comment. When you have decided which is the best answer for your purpose.. then select the comment you feel is best. Mine, Riduce's or anyone elses.. <smile>.

Expert Comment

ID: 2663522
Hi Brindha
  Try following

Before that open new Project
On a for drag CommandButton and List Box

Paste the following Code

Option Explicit
Public fso As New FileSystemObject
Public fld As Folder

Private Sub Command1_Click()
Dim nDirs As Integer, nFiles As integer , lSize As Long Dim sDir As String, sSrchString As String
sDir = InputBox("Please enter the   directory to search", _
                        "FileSystemObjects example", "C:\")
        sSrchString = InputBox("Please enter the file name to search", _
                        "FileSystemObjects example", "vb.ini")
        MousePointer = vbHourglass
        Label1.Caption = "Searching " & vbCrLf & UCase(sDir) & "..."
        lSize = FindFile(sDir, sSrchString, nDirs, nFiles)
        MousePointer = vbDefault
        MsgBox Str(nFiles) & " files found in" & Str(nDirs) & _
               " directories", vbInformation
        MsgBox "Total Size = " & lSize & " bytes"
        End Sub

Private Function FindFile(ByVal sFol As String, sFile As String, _
        nDirs As Integer, nFiles As Integer) As Long
        Dim tFld As Folder, tFil As File, FileName As String
        Set fld = fso.GetFolder(sFol)
        FileName = Dir(fso.BuildPath(fld.Path, sFile), vbNormal Or vbHidden Or vbSystem Or vbReadOnly)
            While Len(FileName) <> 0
                FindFile = FindFile + FileLen(fso.BuildPath(fld.Path, FileName))
                nFiles = nFiles + 1
                List1.AddItem fso.BuildPath(fld.Path, FileName)  ' Load ListBox
                FileName = Dir()  ' Get next file
                Label1 = "Searching " & vbCrLf & fld.Path & "..."
                nDirs = nDirs + 1
            If fld.SubFolders.Count > 0 Then
                For Each tFld In fld.SubFolders
                    FindFile = FindFile + FindFile(tFld.Path, sFile, nDirs, nFiles)
            End If
End Function

if any problem mail me at
Good Luck
LVL 10

Expert Comment

ID: 2663730
Mine's *fast*
<end g>

Expert Comment

ID: 2663758
riduce changed the proposed answer to a comment
LVL 14

Expert Comment

ID: 2663804
Welp.. there ya go Brindha.. an API solution by Caraf_g.. a FSO solution by Jdhananjay.. a pure VB solution from Rudice.. and a file association solution from wsh2.. <smile>.

Now, its your turn to decide which best fills your needs.. Enjoy !!!
LVL 10

Expert Comment

ID: 2663864
There are many ways to skin a cat.

Keep your hands of mine though! Meow...

Expert Comment

ID: 2663937
Hai y u worry Brindha. VB5 has given u the option. Just search for WinSeek.Vbp

That wiil solve your problem. Get back to me. (With points probably)
LVL 10

Expert Comment

ID: 2664056
LVL 14

Expert Comment

ID: 2664427
Gosh caraf_g.. you never cease to stump me.. now what the heck is lolbo(with a hat thing on top)ks?.. <lol>.
LVL 10

Expert Comment

ID: 2668089

closely related term:




They are all Limburgs expressions and as such not really translatable.

Literally, lolbôks would be translated as funnypants, but in English it doesn't have quite the same impact ;-)
LVL 14

Expert Comment

ID: 2668133
<looking at his lap and stating meekly>.. lolboks?.. <sheesh>.
LVL 10

Expert Comment

ID: 2668227
As opposed to Lederhosen which aren't funny at all.

Expert Comment

ID: 2778832
check the samples on the vb6 cd there is a prog on there to do the job

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Enums (shorthand for ‘enumerations’) are not often used by programmers but they can be quite valuable when they are.  What are they? An Enum is just a type of variable like a string or an Integer, but in this case one that you create that contains…
You can of course define an array to hold data that is of a particular type like an array of Strings to hold customer names or an array of Doubles to hold customer sales, but what do you do if you want to coordinate that data? This article describes…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…
Suggested Courses

715 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question