VBA-调用函数返回布尔值以检查文件是否存在
我正在编写一个VBA程序,通过返回布尔值的函数检查文件是否存在。但是,我在“File=FileExists(strDataFileName,strDataPath)”行遇到问题,VBA报告问题是由于类型不匹配造成的。我真的不知道怎么修理它。请帮帮我 p、 抱歉,代码可能有点混乱,因为我是VBA编程的业余爱好者VBA-调用函数返回布尔值以检查文件是否存在,vba,Vba,我正在编写一个VBA程序,通过返回布尔值的函数检查文件是否存在。但是,我在“File=FileExists(strDataFileName,strDataPath)”行遇到问题,VBA报告问题是由于类型不匹配造成的。我真的不知道怎么修理它。请帮帮我 p、 抱歉,代码可能有点混乱,因为我是VBA编程的业余爱好者 Function FileExists(ByVal sPathName As String, Optional Directory As Boolean) As Boolean On Er
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
函数文件以布尔形式存在(ByVal sPathName作为字符串,可选目录作为布尔值)
出错时继续下一步
如果是“我”,那么
如果IsMissing(Directory)或Directory=False,则
FileExists=(Dir$(sPathName)”)
其他的
FileExists=(Dir$(sPathName,vbDirectory)“”)
如果结束
如果结束
端函数
副主席()
常量strDataPath为String=“C:\Users\”
将strFileName设置为字符串
将strDataFileName设置为字符串
将文件设置为布尔值
Dim ExistWS作为布尔值
以工作簿的形式新建
strDataFileName=“过去的数据”
File=FileExists(strDataFileName,strDataPath)
如果File=False,则
设置wbNew=工作簿。添加
Sheets.Add After:=ActiveSheet
SheetName=格式(日期,“dd-mm-yyyy”)
ActiveSheet.Name=SheetName
wbNew.SaveAs文件名:=(strDataPath和strDataFileName),文件格式:=52
新的,结束
其他的
单元格(2,3)=“真”
如果结束
端接头
第二个参数需要一个布尔值来指定它是否为目录。然后,该线路上的更换应能正常工作:
File=FileExists(strDataPath&strDataFileName,false)
第二个参数是布尔值。阅读你的代码,我想如果你把它改成一个字符串,你会成功的
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
函数文件以布尔形式存在(ByVal sPathName作为字符串,可选目录作为字符串)
出错时继续下一步
如果是“我”,那么
如果IsMissing(目录)或Directory=“”,则
FileExists=(Dir$(sPathName)”)
其他的
FileExists=(Dir$(vbDirectory&sPathName)”)
如果结束
如果结束
端函数
别忘了在潜艇上指定文件扩展名。Thz Jimmy!现在可以了!真太赫兹为您及时的帮助!