Solved

Dir command - FIND ??

Posted on 2001-07-19
8
256 Views
Last Modified: 2012-05-04
Hi i am using the Dir(path ,*.doc) to find docs on a given drive

is it possible to serach through all of the givern drive at once including sub directories or is there another better method ??


SILKI
0
Comment
Question by:silki
[X]
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
8 Comments
 
LVL 43

Accepted Solution

by:
TimCottee earned 65 total points
ID: 6297520
Check out the knowledgebase article Q185476 from Microsoft, this gives you two out of three ways to achieve this. I would steer clear of the FileSystemObject personally though it may appear an attractive solution. The API solution may appear more complex but is perhaps the fastest and most efficient solution.

0
 

Expert Comment

by:MarioK
ID: 6297685
Example using the FileSystemObject
Only does the first set of folders at the moment but can be changed to dive in deeper.
----code----
Dim fileSystem, driveCollection
Dim drive, subfolder, usrFolder
Dim usrRootFolder, FileCollection, usrFile
Dim m As String
Dim searchFile As String
   
Set fileSystem = CreateObject("Scripting.FileSystemObject")
Set driveCollection = fileSystem.Drives
searchFile = "test.bat"
For Each drive In driveCollection
  If drive.IsReady Then
  Set usrRootFolder = fileSystem.GetFolder(drive.RootFolder)
  Set subfolder = usrRootFolder.SubFolders
    For Each usrFolder In subfolder
    If fileSystem.FileExists(usrFolder & "\" & searchFile) Then MsgBox "Found"
      Set FileCollection = usrFolder.Files
      m = usrFolder & vbLf
      For Each usrFile In FileCollection
        m = m & usrFile.ShortName & vbLf
      Next
    MsgBox m
    Next
  End If
Next
--code--
MK
0
 

Expert Comment

by:MarioK
ID: 6297703
Example using the FileSystemObject
Only does the first set of folders at the moment but can be changed to dive in deeper.
----code----
Dim fileSystem, driveCollection
Dim drive, subfolder, usrFolder
Dim usrRootFolder, FileCollection, usrFile
Dim m As String
Dim searchFile As String
   
Set fileSystem = CreateObject("Scripting.FileSystemObject")
Set driveCollection = fileSystem.Drives
searchFile = "test.bat"
For Each drive In driveCollection
  If drive.IsReady Then
  Set usrRootFolder = fileSystem.GetFolder(drive.RootFolder)
  Set subfolder = usrRootFolder.SubFolders
    For Each usrFolder In subfolder
    If fileSystem.FileExists(usrFolder & "\" & searchFile) Then MsgBox "Found"
      Set FileCollection = usrFolder.Files
      m = usrFolder & vbLf
      For Each usrFile In FileCollection
        m = m & usrFile.ShortName & vbLf
      Next
    MsgBox m
    Next
  End If
Next
--code--
MK
0
MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

 
LVL 43

Expert Comment

by:TimCottee
ID: 6297745
If you must use FSO here is an example which will perform iteration of folders from a given starting point with full file matching including wildcards:

Private Sub Command1_Click()
    Dim colFiles As New Collection
    Set colFiles = GetFileList("UPF\Personal", "*.*", , True)
    MsgBox colFiles.Count
End Sub

Public Function GetFileList(strFolderPath As String, Optional strExtension As String = "*.*", Optional enuAttributes As FileAttribute = 0, Optional ByVal blnSearchSubFolders As Boolean = False, Optional ByRef colExisting As Collection) As Collection
    'Make sure a reference has been set to Microsoft Scripting Runtime
    'scrrun.dll before attempting to compile this code.
    '(c) TechRepublic, 2001 all rights reserved
    'The Windows Script Host Model must also be installed and registered to use the profile specific
    'switches in the folderpath argument: WSHOM.OCX
    'The folder path parameter may be one of the following:
    '1) A complete folder path either in Drive:\Folder\subfolder or in UNC e.g, \\ServerName\ShareName\Folder\SubFolder
    '2) A special folder
    '   a) WindowsFolder            :WindowsFolder
    '   b) Windows System Folder    :SystemFolder
    '   c) Temporary Files Folder   :TempFolder
    '3) A profile specific path to a system folder this is identified by prefixing with "UPF\" and may be one of the following
    '   a) Administrative Tools
    '   b) AppData
    '   c) Cache
    '   d) Cookies
    '   e) Desktop
    '   f) Favourites
    '   g) History
    '   h) Local AppData
    '   i) My Pictures
    '   j) NetHood
    '   k) Personal AKA My Documents
    '   l) PrintHood
    '   m) Programs
    '   n) Recent
    '   p) SendTo
    '   q) Start Menu
    '   r) Startup
    '   There may be additional options under Windows 9x, Windows 2000 or Windows XP.
    'The extension parameter may be specified either as "txt" to return all files matching this extension
    'or with a wildcarded filename, the wildcard characters "*" and "?" may be used both in the
    'filename and extension parts, following the standard windows rules for these things
    'The blnSearchSubFolders parameter may be used to search only the specified folder (False) or all subfolders (True)
    'The colExisting parameter may be passed an existing collection, this can be used to create a collection first
    'and then run consecutive searches on different criteria and return the result in one collection
    'this is effectively what is achieved by the recursion into this routine when searching
    'all subfolders from the given starting point.
    Dim fs As Scripting.FileSystemObject
    Dim fldr As Scripting.Folder
    Dim subfldr As Scripting.Folder
    Dim f As Scripting.File
    Dim strProfileRoot As String
    'Get the user's special folder root reference
    strProfileRoot = Environ("UserProfile")
    'Get reference to file system
    Set fs = New FileSystemObject
    'Check for a special folder
    Select Case UCase(strFolderPath)
    Case "WINDOWSFOLDER"
        strFolderPath = fs.GetSpecialFolder(0)
    Case "SYSTEMFOLDER"
        strFolderPath = fs.GetSpecialFolder(1)
    Case "TEMPFOLDER"
        strFolderPath = fs.GetSpecialFolder(2)
    End Select
    'Check for a profile specific folder
    If Left$(UCase(strFolderPath), 4) = "UPF\" Then
        'Get rid of the UPF\ part
        strFolderPath = Right$(strFolderPath, Len(strFolderPath) - 4)
        'Get the real location of this folder from the registry
        strFolderPath = strProfileRoot & GetActualPathFromRegistry(strFolderPath)
    End If
    'Check that the folder exists
    If fs.FolderExists(strFolderPath) Then
        'Create a new collection to store the
        'file objects in
        If colExisting Is Nothing Then
            Set GetFileList = New Collection
        Else
            Set GetFileList = colExisting
        End If
        'Get a pointer to the folder
        Set fldr = fs.GetFolder(strFolderPath)
        'Should we search this folder only or include sub folders
        If blnSearchSubFolders Then
            For Each subfldr In fldr.SubFolders
                GetFileList subfldr.Path, strExtension, enuAttributes, blnSearchSubFolders, GetFileList
            Next
        End If
        For Each f In fldr.Files
            blAddToList = True
            'Build a list of files matching the extension
            'we received
            If InStrRev(strExtension, ".") > 0 Then
                'Match a wildcard filename
                blAddToList = f.Name Like strExtension
            Else
                blAddToList = f.Name Like "*." & strExtension
            End If
            If enuAttributes <> 0 And blAddToList Then
                'Check the file attributes by doing a bitwise and
                'on the attributes property for the specified
                'lngAttributes. If none of the bit(s) we are
                'looking for are set then don't add the file
                If (f.Attributes And enuAttributes) = 0 Then
                    blAddToList = False
                End If
            End If
            If blAddToList Then
                'Add the file to the collection
                GetFileList.Add f, f.Path & " : " & f.Name
            End If
            'Go to the next file in the folder
        Next f
    Else
        'oops
        MsgBox strFolderPath & " does not exist"
    End If
    'Clean up by destroying the reference to the FileSystemObject
    Set fs = Nothing
End Function

Public Function GetActualPathFromRegistry(ByVal FolderName As String) As String
    'Declare the object
    Dim wshShell As Object
    Dim strPath As String
    'Create the Windows Scripting Host Shell object
    Set wshShell = CreateObject("WScript.Shell")
    On Error GoTo errBadRead
    'Read the registry for the appropriate value
    strPath = wshShell.RegRead("HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\" & FolderName)
    'trim it up if necessary, remove %USERPROFILE% value from NT, not required on 2000
    strPath = Right$(strPath, Len(strPath) - (InStr(strPath, "\") - 1))
    'Return the value we found
    GetActualPathFromRegistry = strPath
    'Clean up the object
    Set wshShell = Nothing
    Exit Function
errBadRead:
    'Couldn't find the registry key so return unavailable and clean up
    GetActualPathFromRegistry = "Unavailable"
    Set wshShell = Nothing
End Function
0
 
LVL 4

Expert Comment

by:dreamvb
ID: 6298382
Hi have a look at this i found this to be quite usfull before it will serach all of the drive for Files and list them in a list box.

http://www.developers-answers.com/cats/prog/visbas/source/Files/catalog.zip

good luck..
0
 
LVL 16

Expert Comment

by:Richie_Simonetti
ID: 6298851
0
 

Author Comment

by:silki
ID: 6298898
Thanks All

Can I just ask what the problem is with

File System Object

???????????????????????????

SILKI
0
 
LVL 43

Expert Comment

by:TimCottee
ID: 6298965
It adds additional resource requirements to the installation, as you need to reference the scripting runtime or use it latebound with createobject and as it is part of the scripting runtime some system administrators do not allow it to be used as it can be exploited. It is also not as fast as the native methods in many cases. It was designed for use with VBScript which does not have the native methods and also does not have the ability to use API calls.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Have you ever wanted to restrict the users input in a textbox to numbers, and while doing that make sure that they can't 'cheat' by pasting in non-numeric text? Of course you can do that with code you write yourself but it's tedious and error-prone …
Article by: Martin
Here are a few simple, working, games that you can use as-is or as the basis for your own games. Tic-Tac-Toe This is one of the simplest of all games.   The game allows for a choice of who goes first and keeps track of the number of wins for…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
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…

740 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