在VBA中用DIR函数遍历子文件夹出错
Subtest002(folderAsString)anyfsubfolder=Dir(folder,vbDirectory)DoSelectCaseanyfsubfol...
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
从子文件夹中返回上层文件夹中的时候,出错 展开
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
从子文件夹中返回上层文件夹中的时候,出错 展开
展开全部
遇到过同样的问题, 稍微修改了一下可以遍历了。
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
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
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
因为你遍历子文件夹时调用带参数的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
子文件夹遍历结束后,再调用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
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询