2014-10-10 45 views
0

我在寫一個VBA程序來檢查文件是否通過返回布爾值的函數存在。但是,我遇到了「File = FileExists(strDataFileName,strDataPath)」行的問題,VBA報告問題是由於類型不匹配造成的。我真的不知道如何解決它。請幫助傢伙。VBA - 調用函數返回布爾值來檢查文件是否存在

p.s.遺憾的代碼也許有點亂,因爲我在VBA編程的業餘

Function FileExists(ByVal sPathName As String, Optional Directory As Boolean) As Boolean 
On Error Resume Next 
If sPathName <> "" Then 
    If IsMissing(Directory) Or Directory = False Then 
     FileExists = (Dir$(sPathName) <> "") 
    Else 
     FileExists = (Dir$(sPathName, vbDirectory) <> "") 
    End If 
End If 
End Function 

Sub AH() 
Const strDataPath As String = "C:\Users\" 
Dim strFileName As String 
Dim strDataFileName As String 
Dim File As Boolean 
Dim ExistWS as boolean 
Dim wbNew As Workbook 

strDataFileName = "Past Data" 
File = FileExists(strDataFileName, strDataPath) 
If File = False Then 
    Set wbNew = Workbooks.Add 
    Sheets.Add After:=ActiveSheet 
    SheetName = Format(Date, "dd-mm-yyyy") 
    ActiveSheet.Name = SheetName 
    wbNew.SaveAs Filename:=(strDataPath & strDataFileName), FileFormat:=52 
    wbNew.Close 
Else 
    Cells(2,3) = 「TRUE」 
End If 
End Sub 

回答

1

你的第二個參數需要一個boolean指定它是否是一個目錄。
這種替換該行應該再工作:

File = FileExists(strDataPath & strDataFileName, false)

+1

Thz Jimmy!它現在有效! reali thz for yr及時幫助! – 2014-10-10 16:21:32

0

你的第二個參數是一個布爾值。讀你的代碼我認爲,也許如果你改變它爲一個字符串,你會做到這一點。

Function FileExists(ByVal sPathName As String, Optional Directory As String) As Boolean 
On Error Resume Next 
If sPathName <> "" Then 
    If IsMissing(Directory) Or Directory = "" Then 
     FileExists = (Dir$(sPathName) <> "") 
    Else 
     FileExists = (Dir$(vbDirectory & sPathName) <> "") 
    End If 
End If 
End Function 

不要忘了在你的Sub中指定你的文件擴展名。

+0

This Works too!感謝您的幫助RomeuForte! – 2014-10-10 16:22:40