很多时候,在编写VBA代码时,我们发现需要使用一种或另一种形式的文件。 无论执行什么过程,我们都需要确保在指定位置存在文件。 一种保证文件确实存在的方法是,将文件的绝对路径传递给函数,该函数将调查该路径并返回一个布尔值(真/假),以指示文件是否存在。 下面的代码段将做到这一点。 它接受一个表示文件路径的字符串参数,如果存在,则返回True,并且用户可以正常进行;如果不存在,则会出现一个消息框,指示用户该文件在以下位置不存在:被传递给它。
- 功能定义
Public Function fFileExists(strName As String) As Boolean Dim strTempString As String On Error Resume Next 'will check for an Error condition shortly in the Function assignment 'Search for the File with 'any' attribute set. strTempString = Dir$(strName, vbHidden Or vbSystem Or vbArchive Or vbReadOnly) 'If the Length of the FilePath > 0 and no Error condition exists, File exists fFileExists = ((Len(strTempString) > 0) And (Err.Number = 0)) Err.Clear 'Clear the Error Object End Function
- 调用函数
Const strPathToFile As String = "C:\Windows\System32\Import_1.txt" If fFileExists(strPathToFile) Then 'normal processing of the File occurs here Else Dim strBaseFileName As String, strFolderPath As String, Msg As String strBaseFileName = Right$(strPathToFile, Len(strPathToFile) - InStrRev(strPathToFile, "\")) strFolderPath = Left(strPathToFile, InStrRev(strPathToFile, "\")) Msg = strBaseFileName & " was not found in " & strFolderPath & vbCrLf & vbCrLf Msg = Msg & "Please verify your FileName and/or Path, then try again." MsgBox Msg, vbCritical, "Invalid Path" End If
- 如果找不到文件和/或路径,则自定义错误消息(仅文本)
Import_1.txt was not found in C:\Windows\System32\ Please verify your FileName and/or Path, then try again.
- 特别注意事项
- 如果您的文件位于网络驱动器上,则您可能需要增强错误处理代码,因为路径和/或文件名可能是有效的,但是可能还会出现许多其他与网络相关的错误。
- 作为Access开发人员,只要我们尝试以任何方式打开,关闭或处理文件,与上面列出的代码相似的代码应为SOP(标准操作过程)。 我们永远不要假设文件存在,并且它的路径是有效的。 在验证其存在之前尝试对其进行操作将是一种不好的编程习惯。
From: https://bytes.com/topic/access/insights/729467-does-file-exist