vba的dir函数,怎么在一个循环中使用两次,并不会互相冲突
答案:2 悬赏:20 手机版
解决时间 2021-02-08 05:36
- 提问者网友:听门外雪花风
- 2021-02-07 07:29
因为在一个循环,我要想获得不同路径的文件名,所以冲突了。找很久没找到解决方法,请回答的哥哥给代码附加解释,谢谢谢谢谢谢谢啦
最佳答案
- 五星知识达人网友:煞尾
- 2021-02-07 09:08
据资料,dir 不能嵌套使用。
解决办法:可以尝试先将结果保存到数组,再遍历数组各项 dir ;或者可以借用 Scripting.Dictionary 与 dir 相结合起来使用。
提供网络代码供参考:
Public 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 Left(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
End Function
测试函数:
Public Sub a()
Dim a
a = ListFile("F:\VBA\pdf\Excel2007VBA", True, "*.xls")
Range("a1").Resize(UBound(a), 1) = a
End Sub
解决办法:可以尝试先将结果保存到数组,再遍历数组各项 dir ;或者可以借用 Scripting.Dictionary 与 dir 相结合起来使用。
提供网络代码供参考:
Public 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 Left(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
End Function
测试函数:
Public Sub a()
Dim a
a = ListFile("F:\VBA\pdf\Excel2007VBA", True, "*.xls")
Range("a1").Resize(UBound(a), 1) = a
End Sub
全部回答
- 1楼网友:封刀令
- 2021-02-07 10:24
你好!
如果你的参数不含通配符,就没有任何冲突
如果含有通配符,可以用字符串数组保存一个通配符得到的全部结果
然后在搜索另一个通配符,结果都保存到这个字符串数组
最后过滤数组得到你想要的结果
不会有冲突了
仅代表个人观点,不喜勿喷,谢谢。
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯