3 回答
TA贡献1856条经验 获得超5个赞
因为你遍历子文件夹时调用带参数的Dir(folder, vbDirectory),
子文件夹遍历结束后,再调用Dir默认的路径仍然是子文件夹,已经遍历完了,所以出错。
建议使用下面方法:
Sub test002(folderspec)
Dim fs, f, f1, sf, fc
Dim mypath As String, fn As String
Dim i As Long, lmyRow As Long
On Error Resume Next
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFolder(folderspec)
Set sf = f.SubFolders
Set fc = f.Files
For Each f1 In sf
fn = f1.Name
mypath = folderspec & fn & "\"
ShowFolderList mypath
Next
For Each f1 In fc
fn = f1.Name
Next
End Sub
TA贡献1820条经验 获得超9个赞
遇到过同样的问题, 稍微修改了一下可以遍历了。
Sub test002(folder As String)
If Right(folder, 1) <> "\" Then
folder = folder & "\"
End If
anyfsubfolder = Dir(folder, vbDirectory)
Do
Select Case anyfsubfolder
Case ""
Exit Do
Case "."
Case ".."
Case Else
If GetAttr(folder & anyfsubfolder) And vbDirectory Then
'MsgBox folder & anyfsubfolder
Call test002(folder & anyfsubfolder)
End If
End Select
'加上以下代码, 还原Dir函数运行环境
subfoldervisited = Dir(folder, vbDirectory)
Do While subfoldervisited <> anyfsubfolder
subfoldervisited = Dir
Loop
'Dir已恢复至递归调用前
anyfsubfolder = Dir
Loop
End Sub
添加回答
举报