自定义函数:查找文件路径的问题,返回值怎么一直为空
foldername = qtpdirfilename ="标准版测试用例_new.xls"
y =FindFilePath(foldername,filename)
msgbox y '为什么这里打印为空
'在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)
IfUtilFolder 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 notfind 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 如果定义了D:则加相对路径。 如果没定义文件夹,则加个绝对路径 路径必须用“”引号 问题解决了,是循环套循环引起的问题,终于可以轻松了 吧正确的放上来共享一下吧 找到了.是变量作用域的问题.
Dim tpath 改为定义成全局变量
FindFilePath = CStr(tpath) 不要在else下面
改为放最后一行就可以了.
[ 本帖最后由 onlonely 于 2009-6-13 14:09 编辑 ] 花了点时间解决这个问题。放出来共享下....(PS:貌似上面很多人都已经解决了...) foldername ="G:\Test2"
filename ="标准版测试用例_new.xls"
Dim find,temp
find = False
call FindFilePath(foldername,filename)
msgbox temp '为什么这里打印为空
'在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)
IfUtilFolder 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 notfind 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
页:
[1]