在VBA中用DIR函数遍历子文件夹出错?

Sub test002(folder As String)
anyfsubfolder = Dir(folder, vbDirectory)
Do
Select Case anyfsubfolder
Case ""
Exit Do
Case "."
Case ".."
Case Else
If GetAttr(folder & anyfsubfolder) And vbDirectory Then
Call test002(folder & anyfsubfolder & "\")
End If
End Select
anyfsubfolder = Dir ‘《《-----在这个地方出错
Loop
End Sub

从子文件夹中返回上层文件夹中的时候,出错




慕码人8056858
浏览 1494回答 3
3回答

缥缈止盈

图片弹出的意思是:无效的过程调用。dir是vba内置函数,需要参数运行。

RISEBY

因为你遍历子文件夹时调用带参数的Dir(folder, vbDirectory),子文件夹遍历结束后,再调用Dir默认的路径仍然是子文件夹,已经遍历完了,所以出错。建议使用下面方法:Sub test002(folderspec)Dim fs, f, f1, sf, fcDim mypath As String, fn As StringDim i As Long, lmyRow As LongOn Error Resume NextSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set sf = f.SubFoldersSet fc = f.FilesFor Each f1 In sffn = f1.Namemypath = folderspec & fn & "\"ShowFolderList mypathNextFor Each f1 In fcfn = f1.NameNextEnd Sub

慕妹3146593

遇到过同样的问题, 稍微修改了一下可以遍历了。Sub test002(folder As String)If Right(folder, 1) <> "\" Thenfolder = folder & "\"End Ifanyfsubfolder = Dir(folder, vbDirectory)DoSelect Case anyfsubfolderCase ""Exit DoCase "."Case ".."Case ElseIf GetAttr(folder & anyfsubfolder) And vbDirectory Then'MsgBox folder & anyfsubfolderCall test002(folder & anyfsubfolder)End IfEnd Select'加上以下代码, 还原Dir函数运行环境subfoldervisited = Dir(folder, vbDirectory)Do While subfoldervisited <> anyfsubfoldersubfoldervisited = DirLoop'Dir已恢复至递归调用前anyfsubfolder = DirLoopEnd Sub
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python