Dir 函数

返回与指定的搜索路径相匹配的驱动器或目录中的某个文件、某个目录或所有文件和目录的名称。

语法:


Dir [(PathName As String [, Attributes As Integer])]

返回值:

字符串

参数:

PathName: Any string expression that specifies the search path, directory or file. This argument can only be specified the first time that you call the Dir function. If you want, you can enter the path in URL notation.

Attributes:Any integer expression that specifies bitwise file attributes. The Dir function only returns files or directories that match the specified attributes. You can combine several attributes by adding the attribute values:

0: 普通文件。

16: 仅返回目录名称。

使用此属性来检查文件或目录是否存在,或者确定指定目录下的所有文件或文件夹。

要检查文件是否存在,请输入完整的文件路径和名称。如果文件或目录的名称不存在,Dir 函数将返回一个零长度字符串 ("")。

要生成特定目录下所有现有文件的列表,请执行以下操作: 第一次调用 Dir 函数时,指定完整的文件搜索目录,如「D:\Files\*.ods」。如果指定的路径正确,并且至少搜索到一个文件,Dir 函数将返回与搜索路径相匹配的第一个文件的名称。要返回与路径相匹配的其他文件的名称,请再次调用 Dir 函数,但不用带自变量。

要仅返回目录,请使用该属性参数。这也同样适用于确定卷 (例如硬盘分区) 的名称。

错误代码:

5 无效的过程调用

53 未找到文件

示例:


Sub ExampleDir
' 显示所有文件和目录
Dim sPath As String
Dim sDir As String, sValue As String
    sDir="目录列表:"
    sPath = CurDir
    sValue = Dir$(sPath + getPathSeparator + "*",16)
    Do
        If sValue <> "." And sValue <> ".." Then
            If (GetAttr( sPath + getPathSeparator + sValue) And 16) >0 Then
                ' 获取目录
                sDir = sDir & chr(13) & sValue
            End If
        End If
        sValue = Dir$
    Loop Until sValue = ""
    MsgBox sDir,0,sPath
End Sub

请支持我们!