Dir()函数的理解

' Display the names in C:\ that represent directories. MyPath = "c:\" ' Set the path. MyName = Dir(MyPath, vbDirectory) ' Retrieve the first entry. Do While MyName <> "" ' Start the loop. ' Use bitwise comparison to make sure MyName is a directory. If (GetAttr(MyPath & MyName) And vbDirectory) = vbDirectory Then ' Display entry only if it's a directory. MsgBox(MyName) End If MyName = Dir() ' Get next entry. Loop 

我正在看上面的代码。 我特别不明白“MyName = Dir()”是干什么的。 它被评论它得到下一个条目,但我不明白它是如何得到下一个条目 – 具体是什么Dir()在做什么?

Dir是具有边缘效应的function。

第一次调用DirMyName = Dir(MyPath, vbDirectory)初始化Dir内部并返回第一个目录条目。

随后对Dir调用使用相同的上下文,逐个产生MyPath目录内容。

这不是可重入的(这也是为什么你不能使用Dir来嵌套/recursion多个循环),不是很优雅,但这就是它的工作原理。

根据Dir() MSDN ,它

返回一个string,该string表示与指定的模式或文件属性或驱动器的卷标匹配的文件,目录或文件夹的名称。