我编写了这段代码来遍历文件夹并在找到“.c”文件时退出该函数。理想情况下,它应该返回“.c”文件的路径。但它返回空字符串。
tval = 1
Function findStlcode(objFSO,fFolder,folderName)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set Folder = objFSO.GetFolder(fFolder)
Set colfiles = Folder.Files
For Each objFile In colfiles
strFilename = objFile.name
If strcomp(strFilename,folderName & ".c",vbTextCompare) = 0 Then
findStlcode = fFolder & "\" & folderName & ".c"
tval = tval + 1
Exit Function
End If
Next
For Each Subfolder In Folder.SubFolders
If tval = 1 Then
xx = findStlcode(objFSO, Subfolder.Path, folderName)
End If
Next
End Function
答案 0 :(得分:2)
将FOR循环内容更改为以下,将xx更改为findStlcode,它应该可以正常工作
strFilename = objFile.name
If Right(strFilename, 2) = ".c" Then
findStlcode = fFolder & "\" & strFilename
tval = tval + 1
Exit Function
End If
完整的代码
tval = 1
Function findStlcode(objFSO,fFolder)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set Folder = objFSO.GetFolder(fFolder)
Set colfiles = Folder.Files
For Each objFile In colfiles
strFilename = objFile.name
If Right(strFilename, 2) = ".c" Then
findStlcode = fFolder & "\" & strFilename
tval = tval + 1
Exit Function
End If
Next
For Each Subfolder In Folder.SubFolders
If tval = 1 Then
findStlcode = findStlcode(objFSO, Subfolder.Path)
End If
Next
End Function
调用函数
Set objFSO = CreateObject("Scripting.FileSystemObject")
Wscript.Echo findStlcode(objFSO, "C:\")
答案 1 :(得分:0)
问题的根本原因是你的函数实际上没有返回路径(通过将其分配给函数名),正如其他人已经指出的那样。
但是,您可能希望解决一些与实施相关的问题:
objFSO
是没有意义的。在几乎每种情况下,最好将FileSystemObject
实例创建为全局(单例)对象,并在脚本中的任何位置使用它。GetExtensionName
)中提取扩展程序。这样的东西就足够了:
Set fso = CreateObject("Scripting.FileSystemObject")
Function findStlcode(fldr)
Dim f, sf, path
For Each f In fldr.Files
If LCase(fso.GetExtensionName(f)) = "c" Then
path = f.Path
Exit For
End If
Next
For Each sf In fldr.SubFolders
If IsEmpty(path) Then path = findStlcode(sf)
Next
findStlcode = path
End Function
startFolder = "C:\some\folder"
cfile = findStlCode(fso.GetFolder(startFolder))