(Q) How do I search a hard drive for a file given only it's name and retrieve the path
to it??
(A) The first example is applicable only for Access 97. For Access 95, see the
alternate method.
You can use the new Office FileSearch object for this. Before using the code, make sure
"Microsoft Office 8.0 Object Library" (typically referenced to MSO97.DLL under
Office folder) is selected under Tools/References.
Paste the following code in a new module:
Function fReturnFilePath(strFilename As String, _
strDrive As String) As String
Dim varItm As Variant
Dim strFiles As String
Dim strTmp As String
If InStr(strFilename, ".") = 0 Then
MsgBox "Sorry!! Need the complete name", vbCritical
Exit Function
End If
strFiles = ""
With Application.FileSearch
.NewSearch
.LookIn = strDrive
.SearchSubFolders = True
.FileName = strFilename
.MatchTextExactly = True
.FileType = msoFileTypeAllFiles
If .Execute > 0 Then
For Each varItm In .FoundFiles
strTmp = fGetFileName(varItm)
If strFilename = strTmp Then
fReturnFilePath = varItm
Exit Function
End If
Next varItm
End If
End With
End Function
Private Function fGetFileName(strFullPath) As String
Dim intPos As Integer, intLen As Integer
intLen = Len(strFullPath)
If intLen Then
For intPos = intLen To 1 Step -1
If Mid$(strFullPath, intPos, 1) = "\" Then
fGetFileName = Mid$(strFullPath, intPos + 1)
Exit Function
End If
Next intPos
End If
End Function
Now from your code, call the function as
strFilePath=fReturnFilePath("network.wri","C:")
(Note: Depending on whether you have Microsoft Office's FindFast turned on or not, the
search might take a few seconds.)
Alternate: For Access 95 (or for Access 97 also), you can use the following function as
a substitute to FileSearch object.
Private Declare Function apiSearchTreeForFile Lib "ImageHlp.dll" Alias _
"SearchTreeForFile" (ByVal lpRoot As String, ByVal lpInPath _
As String, ByVal lpOutPath As String) As Long
Function fSearchFile(ByVal strFilename As String, _
ByVal strSearchPath As String) As String
Dim lpBuffer As String
Dim lngResult As Long
fSearchFile = ""
lpBuffer = String$(1024, 0)
lngResult = apiSearchTreeForFile(strSearchPath, strFilename, lpBuffer)
If lngResult <> 0 Then
If InStr(lpBuffer, vbNullChar) > 0 Then
fSearchFile = Left$(lpBuffer, InStr(lpBuffer, vbNullChar) - 1)
End If
End If
End Function
|