如何用VBA遍历指定目录下的所有子文件夹Excel文件的所有工作表
4个回答
展开全部
下面的代码是手工码的,不晓得有没有问题。
sub test()
dim f as string,mPath as string,Wb as workbook,Sh as workSheet
if workbooks.count>1 then msgbox "关闭其他工作簿!":exit sub
mPath = "D:\临时文件夹\" '指定路径,注意分层标记\
f=dir(mPath & "*.xls*")
do while f<>""
if f<>thisworkbook.name then
set Wb=workbooks.open(mPath & f) '只读方式打开
with Wb
for each Sh in .workSheets
'对工作表进行操作的代码段,自己写。
next
end with
wb.close 0 '关闭文件
end if
f=dir '枚举,以访问下一个工作簿。
loop
end sub
2018-03-01
展开全部
Private Function ListFile(MuLu As String, Zi As Boolean, Optional LeiXing As String = "")
Dim MyFile As String, ms As String
Dim arr, brr, x
Dim i As Integer
Set d = CreateObject("Scripting.Dictionary")
If Right(MuLu, 1) <> "\" Then MuLu = MuLu & "\"
d.Add MuLu, ""
i = 0
Do While i < d.Count
brr = d.keys
MyFile = Dir(brr(i), vbDirectory)
Do While MyFile <> ""
If MyFile <> "." And MyFile <> ".." Then
If (GetAttr(brr(i) & MyFile) And vbDirectory) = vbDirectory Then d.Add (brr(i) & MyFile & "\"), ""
End If
MyFile = Dir
Loop
If Zi = False Then Exit Do
i = i + 1
Loop
If LeiXing = "" Then
ListFile = Application.Transpose(d.keys)
Else
For Each x In d.keys
MyFile = Dir(x & LeiXing)
Do While MyFile <> ""
ms = ms & x & MyFile & ","
MyFile = Dir
Loop
If Zi = False Then Exit For
Next
If ms = "" Then ms = "没有符合要求的文件,"
ListFile = Application.Transpose(Split(ms, ","))
End If
Set d = Nothing
End Function
这个是我找到(抄袭)的一段代码,查找文件夹下面的子文件夹,文件的,我想你应该需要这个,列出子文件夹,然后所有遍历,三个参数,mulu是指定的路径,zi是是否查询子文件夹,leixin是文件类型,少少修改应该能满足你的需求
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
用字典比较方便,不过总的来说代码还是比较复杂的。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
Sub test()
Dim f As String, mPath As String, Wb As Workbook, Sh As Worksheet
If Workbooks.Count > 1 Then MsgBox "关闭其他工作簿!": Exit Sub
mPath = "D:\临时文件夹\" '指定路径,注意分层标记\
f = Dir(mPath & "*.xls*")
Do While f <> ""
If f <> ThisWorkbook.Name Then
Set Wb = Workbooks.Open(mPath & f) '只读方式打开
With Wb
For Each Sh In .Worksheets
'对工作表进行操作的代码段,自己写。
Next
End With
Wb.Close 0 '关闭文件
End If
f = Dir '枚举,以访问下一个工作簿。
Loop
End Sub
网上复制的,大概看了下,应该没有问题。
Dim f As String, mPath As String, Wb As Workbook, Sh As Worksheet
If Workbooks.Count > 1 Then MsgBox "关闭其他工作簿!": Exit Sub
mPath = "D:\临时文件夹\" '指定路径,注意分层标记\
f = Dir(mPath & "*.xls*")
Do While f <> ""
If f <> ThisWorkbook.Name Then
Set Wb = Workbooks.Open(mPath & f) '只读方式打开
With Wb
For Each Sh In .Worksheets
'对工作表进行操作的代码段,自己写。
Next
End With
Wb.Close 0 '关闭文件
End If
f = Dir '枚举,以访问下一个工作簿。
Loop
End Sub
网上复制的,大概看了下,应该没有问题。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询