创建和删除文件夹
注意: 为简便起见,下面的示例使用本主题中的“ 确定文件夹和文件存在” 示例中的 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