Sub 文件是否存在() 'dir函數+帶文件名稱的路徑
a = Dir("C:\Users\Administrator\Desktop\vba筆記\15.操作工作簿\123.xls")
If a = "" Then
MsgBox "不存在"
Else
MsgBox "存在"
End If
End Sub
將上面的代碼改為自定義函數,方便引用。
Private Function FileExists(fname) As Boolean
Dim x As String
x = Dir(fname)
If x <> "" Then FileExists = True _
Else FileExists = False
End Function
用上面的自定義函數判斷工作簿是否存在,參數是--帶文件名的路徑。
Sub 文件存在嗎1()
Dim sFileName As String
sFileName = "C:\Users\Administrator\Desktop\vba筆記\15.操作工作簿\小貓.xlsx"
If FileExists(sFileName) Then
MsgBox sFileName & " 存在"
Else
MsgBox sFileName & " 不存在"
End If
End Sub