Public Function IsFilePathValid(sFilePath As String, Optional bExists As Boolean = False) As Boolean
On Error GoTo handleError
sFilePath = Trim(sFilePath)
If sFilePath = "" Then
IsFilePathValid = False
Else
If Len(sFilePath) < 4 Then 'c:\t
IsFilePathValid = False
Else
If Mid(sFilePath, 2, 2) <> ":\" Then
IsFilePathValid = False
Else
If sFilePath Like "*\" Then
IsFilePathValid = False
Exit Function
Else
End If
If bExists Then
If GetAttr(sFilePath) And vbDirectory Then
IsFilePathValid = False
Exit Function
End If
If Not IsFileExists(sFilePath) Then
IsFilePathValid = False
Exit Function
End If
End If
顶暴风雨老大的,我再补充:假定文件存在的情况下,这个是标准答案。
Private Declare Function GetFileAttributes Lib "kernel32" Alias "GetFileAttributesA" (ByVal lpFileName As String) As Long
Private Const FILE_ATTRIBUTE_DIRECTORY = &H10
Private Const INVALID_HANDLE_VALUE = -1
Function FileExists(ByVal FileName As String) As Boolean
Dim r As Long
r = GetFileAttributes(FileName)
FileExists = r <> INVALID_HANDLE_VALUE And (Not r And FILE_ATTRIBUTE_DIRECTORY)
End Function
没必要这样复杂。在工程中引用Microsoft Scriping Runtime,然后定义:
dim fso As New Scripting.FileSystemObject
if fso.FolderExists(sPath) then
msgbox "路径存在"
else
msgbox "路径不存在"
end if