Dir Function

傳回與指定的搜尋路徑相符的磁碟機或目錄中的某個檔案、某個目錄或所有檔案和目錄的名稱。

語法

Dir [(Text As String) [, Attrib As Integer]]

傳回值類型

字串型

參數:

Text:用於指定搜尋路徑、目錄或檔案的任意字串型表示式。只能在第一次呼叫 Dir 函式時指定此引數。如果需要,您也可以用 URL 表示法輸入路徑。

Attrib:用於指定逐位元檔案屬性的任意整型表示式。Dir 函式只傳回與指定屬性相符的檔案或目錄。透過將屬性值相加,您可以將多個屬性組合起來:

0 : 一般檔案。

16 : 僅傳回目錄的名稱。

使用此屬性來檢查檔案或目錄是否存在,或者確定指定目錄下的所有檔案或資料夾。

若要檢查檔案是否存在,請輸入檔案的完整路徑和名稱。如果檔案或目錄名稱不存在,Dir 函式將傳回一個零長度字串 ("")。

To generate a list of all existing files in a specific directory, proceed as follows: The first time you call the Dir function, specify the complete search path for the files, for example, "D:\Files\*.ods". If the path is correct and the search finds at least one file, the Dir function returns the name of the first file that matches the search path. To return additional file names that match the path, call Dir again, but with no arguments.

To return directories only, use the attribute parameter. The same applies if you want to determine the name of a volume (for example, a hard drive partition).

錯誤代碼:

5 無效的程序呼叫

53 找不到檔案

示例:

Sub ExampleDir

REM 顯示所有檔案和目錄

Dim sPath As String

Dim sDir As String, sValue As String

    sDir="Directories:"

    sPath = CurDir

    sValue = Dir$(sPath + getPathSeparator + "*",16)

    Do

        If sValue <> "." And sValue <> ".." Then

            If (GetAttr( sPath + getPathSeparator + sValue) And 16) >0 Then

                REM 獲取目錄

                sDir = sDir & chr(13) & sValue

            End If

        End If

        sValue = Dir$

    Loop Until sValue = ""

    MsgBox sDir,0,sPath

End Sub