'在foldername文件夹及其子文件夹下找到一个名字为filename的文件的路径
Function FindFilePath(foldername,filename)
Dim fso,UtilFolder,UtilFolderCollection
Dim Find
Dim tpath
find = False
Set fso = CreateObject("Scripting.FileSystemObject")
On error resume next
Set UtilFolder=fso.GetFolder(foldername)
If UtilFolder is nothing Then
msgbox "FindFilePath的foldername参数不正确"
End If
'搜索当前所有子目录
For each f in UtilFolder.files
If StrComp(Lcase(f.name),Lcase(trim(filename))) = 0 Then
find = True
tpath = f.path
Exit For
End If
Next
If not find Then
Set UtilFolderCollection = UtilFolder.SubFolders
If Not UtilFolderCollection Is Nothing Then '如果子目录不为空
For each ufolder in UtilFolderCollection
FindFilePath ufolder,filename
Next
End If
Else
FindFilePath = CStr(tpath)
MsgBox "haha:" & FindFilePath '只打印一次,FindFilePath能取到路径
End If
Set UtilFolder = Nothing
Set UtilFolderCollection = Nothing
Set fso = Nothing
End Function作者: lin85210 时间: 2009-6-12 16:57
如果定义了D: 则加相对路径。 如果没定义文件夹,则加个绝对路径 路径必须用“”引号作者: hhhsmileyangxue 时间: 2009-6-12 18:02
问题解决了,是循环套循环引起的问题,终于可以轻松了作者: blizzardlyk 时间: 2009-6-12 18:22
吧正确的放上来共享一下吧作者: onlonely 时间: 2009-6-13 11:42
找到了.是变量作用域的问题.
Dim tpath 改为定义成全局变量
FindFilePath = CStr(tpath) 不要在else下面
改为放最后一行就可以了.
'在foldername文件夹及其子文件夹下找到一个名字为filename的文件的路径
Function FindFilePath(foldername,filename)
Dim fso,UtilFolder,UtilFolderCollection
' Dim Find
Dim tpath
Set fso = CreateObject("Scripting.FileSystemObject")
' On error resume next
Set UtilFolder=fso.GetFolder(foldername)
If UtilFolder is nothing Then
msgbox "FindFilePath的foldername参数不正确"
End If
'搜索当前所有子目录
If not find Then
For each f in UtilFolder.files
If StrComp(Lcase(f.name),Lcase(trim(filename))) = 0 Then
find = True
tpath = f.path
' FindFilePath = CStr(tpath)
temp = Cstr(tpath)
Exit For
End If
Next
End If
If not find Then
Set UtilFolderCollection = UtilFolder.SubFolders
If Not UtilFolderCollection Is Nothing Then '如果子目录不为空
For each ufolder in UtilFolderCollection
FindFilePath ufolder,filename
Next
End If
Else
' FindFilePath = CStr(tpath)
' MsgBox "haha:" & FindFilePath '只打印一次,FindFilePath能取到路径
' find = True
End If
Set UtilFolder = Nothing
Set UtilFolderCollection = Nothing
Set fso = Nothing
End Function