VBA-在子中调用Dir()时使用Dir()循环 [英] VBA - Looping with Dir() when Dir() is called in a sub

查看:250
本文介绍了VBA-在子中调用Dir()时使用Dir()循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下文件夹遍历:

I'm looping through a folder using :

Dim file As Variant
file = Dir(myFolder)

While (file <> "" )
    mySub file       '<= this sub use Dir() hundreds of times  !!!
    file = Dir()
Wend

mySub 打破了 Dir循环,因为它给了我另一个文件夹的下一个文件。

mySub breaks the Dir loop since it give me the next file of a different folder.

有解决此限制的简便方法吗?如果没有,您将如何进行?

Is there a easy way to work around that limitation ? If not, how would you proceed ?

我当前正在使用运行第一个循环将文件名存储在 Array 中,然后运行第二个循环来处理 Array

I'm currently using running a first loop storing the filename in an Array, then running a second loop processing mySub from the Array :

Dim file As Variant
file = Dir(myFolder)

Dim myArray() as String
Redim myArray(0)

While (file <> "" )
    Redim Preserve myArray(Ubound(myArray) + 1)
    myArray(Ubound(myArray)) = file
    file = Dir()
Wend

Dim n as Integer
For n = 1 to Ubound(myArray)
    mySub myArray(n)
Next


推荐答案

函数 Dir 使用st Atic迭代器。因此,如果在子函数中调用它,它将从主函数中初始化它。

The function Dir uses a static iterator. Thus if you call it in a sub function, it will initialize the one from the main function.

要使用 Dir 再次在子函数中,您需要在调用子函数(这是您当前的解决方案)之前使用主函数的所有结果。

To use Dir again in a sub function, you need to consume all the results from the main function before calling the sub function, which is your current solution.

但是,调用 Redim Preserve 附加新项的效率很低。
而是定义数组的初始大小,并在需要时将大小增加2:

However, calling Redim Preserve to append a new item is rather inefficient. Instead define an initial size for the array, and increase the size by 2 when required:

Dim file As String, n As Long, i As Long
ReDim myArray(0 To 25)

file = Dir("c:\")

Do While Len(file)
  If n = UBound(myArray) Then ReDim Preserve myArray(n * 2)
  myArray(n) = file
  n = n + 1
  file = Dir()
Loop

For i = 0 To n - 1
  mySub myArray(i)
Next

请注意,您也可以使用 Scripting.FileSystemObject 的实例,但是效率低于 Dir(),仅在Windows上有效。

Note that you could also use an instance of Scripting.FileSystemObject, but it's less efficient that Dir() and it works on Windows only.

这篇关于VBA-在子中调用Dir()时使用Dir()循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆