在VBA中用DIR函数遍历子文件夹出错
答案:3 悬赏:30 手机版
解决时间 2021-12-01 07:07
- 提问者网友:疯孩纸
- 2021-11-30 17:36
在VBA中用DIR函数遍历子文件夹出错
最佳答案
- 五星知识达人网友:夜余生
- 2021-11-30 17:49
因为你遍历子文件夹时调用带参数的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
全部回答
- 1楼网友:过活
- 2021-11-30 19:36
图片弹出的意思是:无效的过程调用。
dir是vba内置函数,需要参数运行。
dir是vba内置函数,需要参数运行。
- 2楼网友:行雁书
- 2021-11-30 18:36
遇到过同样的问题, 稍微修改了一下可以遍历了。
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
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯