VBA - 调用函数返回布尔值以检查文件是否存在

时间:2014-10-10 15:48:38

标签: vba

我正在编写一个VBA程序,通过返回布尔值的函数检查文件是否存在。但是,我遇到了“File = FileExists(strDataFileName,strDataPath)”这一行的问题,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

2 个答案:

答案 0 :(得分:1)

你的第二个参数需要一个布尔值来指定它是否是一个目录 然后,该行上的替换应该起作用:

File = FileExists(strDataPath & strDataFileName, false)

答案 1 :(得分: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。

中指定您的文件扩展名