'以下代码判断一个文件夹是否存在,如果不存在,则创建它:
‘引用Microsoft Scripting Runtime
’创建一个指定的无限层文件夹
Public Function CreateDirectory(ByVal strDirectory As String) As Boolean
On Error GoTo ErrMsg
Dim Status
Dim fso As FileSystemObject
Dim strTempDir As String
Dim intPos As Integer
Screen.MousePointer = 11
CreateDirectory = False
’字符串是否为空
If strDirectory = "" Then GoTo ExitLab
’首先检查文件夹是否已经存在
Set fso = New FileSystemObject
If fso.FolderExists(strDirectory) = True Then
’已经存在
CreateDirectory = True
GoTo ExitLab
Else
If MsgBox("您输入的安装目录不存在,要创建该目录吗?", _
vbQuestion + vbYesNo + vbDefaultButton1, "询问") = vbNo Then GoTo ExitLab
End If
If Right(strDirectory, 1) <> "\" Then
strDirectory = strDirectory & "\"
End If
’不存在的情况
intPos = InStr(1, strDirectory, "\")
If intPos < 1 Then
MsgBox "您输入的文件夹不规范,请重新设置!", vbInformation, "提示"
GoTo ExitLab
End If
Do
strTempDir = Left(strDirectory, intPos - 1)
If fso.FolderExists(strTempDir) = False Then
fso.CreateFolder strTempDir
End If
例:
引用Microsoft Script Control 1.0
Microsoft Scripting Runtime
Function CheckFolder(FoldrPath As String) As Boolean
Dim Exists As Boolean, CreateIt
Dim fso As New FileSystemObject
If (fso.FolderExists(FoldrPath)) Then
Exits = True
Else
Exits = False
'不存在则建立
Set CreateIt = fso.CreateFolder(FoldrPath)
End If
'值返回函数
CheckFolder = Exits
End Function
检验程式
Private Sub Form_Load()
Dim a As Boolean
a = CheckFolder("C:\新建文件夹")
MsgBox a
End Sub