在通过Excel VBA打开文件之前,如何检查文件是否存在?

Sub Auto_Open() myRoutine End Sub Sub myRoutine() Workbooks.Open ("C:\Users\mdowney\Desktop\Testing\OPEN_N_CLOSE.xls") End Sub 

我有这个文件来打开一个文件来locking和解锁电子表格。 如何设置myRoutine子例程,以便检查文件是否在第一个位置? 如果是,则子例程应该运行。 否则,它不应该给我一个错误信息。

使用Dir

码:

 Sub myRoutine() Dim FilePath As String FilePath = "C:\Users\mdowney\Desktop\Testing\OPEN_N_CLOSE.xls" If Dir(FilePath) <> "" Then Workbooks.Open FilePath Else MsgBox "File doesn't exist." End If End Sub 

结果:

在这里输入图像说明

Dir更多应用程序和用法可以在这里find。

还有其他一些选项来检查文件是否存在在这里讨论。

我去了一个amackay11使用 Scripting.FileSystemObject的变体:

 ' Check if a file exists Function fileExists(s_directory As String, s_fileName As String) As Boolean Dim obj_fso As Object Set obj_fso = CreateObject("Scripting.FileSystemObject") fileExists = obj_fso.fileExists(s_directory & "\" & s_fileName) End Function