vba的dir函数,怎么在一个循环中使用两次,并不会互相冲突

因为在一个循环,我要想获得不同路径的文件名,所以冲突了。找很久没找到解决方法,请回答的哥哥给代码附加解释,谢谢谢谢谢谢谢啦

据资料,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
温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-06-12
如果你的参数不含通配符,就没有任何冲突
如果含有通配符,可以用字符串数组保存一个通配符得到的全部结果
然后在搜索另一个通配符,结果都保存到这个字符串数组
最后过滤数组得到你想要的结果
不会有冲突了追问

可以代码说明嘛

追答

你都没有代码,也不知道你的问题具体是什么,我也只能瞎猜你的意思。没有代码就只能空谈了。也不知道你说的冲突是指什么。

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网