建立和刪除資料夾

注意: 為簡便起見,下面的示例使用本主題中的“ 確定資料夾和檔案存在” 示例中的 FolderExists 功能。

MkDir 語句可用於建立新資料夾。它接受包含驅動器號(C:\Foo),UNC 名稱(\\Server\Foo),相對路徑(..\Foo)或當前工作目錄(Foo)的路徑。

如果省略驅動器或 UNC 名稱(即\Foo),則會在當前驅動器上建立該資料夾。這可能與當前工作目錄相同或不同。

Public Sub MakeNewDirectory(ByVal pathName As String)
    'MkDir will fail if the directory already exists.
    If FolderExists(pathName) Then Exit Sub
    'This may still fail due to permissions, etc.
    MkDir pathName
End Sub

RmDir 語句可用於刪除現有資料夾。它接受與 MkDir 相同形式的路徑,並使用與當前工作目錄和驅動器相同的關係。請注意,該語句類似於 Windows rd shell 命令,因此如果目標目錄不為空,將丟擲執行時錯誤 75:“路徑/檔案訪問錯誤”。

Public Sub DeleteDirectory(ByVal pathName As String)
    If Right$(pathName, 1) <> "\" Then
        pathName = pathName & "\"
    End If
    'Rmdir will fail if the directory doesn't exist.
    If Not FolderExists(pathName) Then Exit Sub
    'Rmdir will fail if the directory contains files.
    If Dir$(pathName & "*") <> vbNullString Then Exit Sub
    
    'Rmdir will fail if the directory contains directories.
    Dim subDir As String
    subDir = Dir$(pathName & "*", vbDirectory)
    Do
        If subDir <> "." And subDir <> ".." Then Exit Sub
        subDir = Dir$(, vbDirectory)
    Loop While subDir <> vbNullString
    
    'This may still fail due to permissions, etc.
    RmDir pathName
End Sub