VBA – msgbox文件未find时

当找不到文件TestData.xlsx时,我想要msgbox显示“找不到文件”。 谢谢

Sub check() Dim i As Long '~~> From Row 5 to row 10 '~~> Chnage as applicable For i = 5 To 10 Sheets("Sheet1").Range("F" & i).Formula = _ "=VLookup((CONCATENATE(C1,"" "",C" & i & _ ")),'C:\Documents[TestData.xlsx]Sheet1'!$A$2:$G$28,7, FALSE)" Sheets("Sheet1").Range("F" & i).Value = Sheets("Sheet1").Range("F" & i).Value Next i End Sub 

在for循环之前检查文件:

 If Dir$("C:\Documents\TestData.xlsx") = "" Then MsgBox "File not found" Exit Sub End If 

添加对“Microsoft脚本运行时”的引用

菜单路径ReferenceWindow

接着:

 Dim fso As New FileSystemObject If Not fso.FileExists("C:\Documents\TestData.xlsx") Then MsgBox "File Not Found." 

这将工作。

 Sub test() sPath = "C:\Documents\TestData.xlsx" 'Test if directory or file exists If File_Exists(sPath) Then MsgBox sPath & " exists!" Else MsgBox sPath & " does not exist." End If End Sub Private Function File_Exists(ByVal sPathName As String, Optional Directory As Boolean) As Boolean 'Returns True if the passed sPathName exist 'Otherwise returns False On Error Resume Next If sPathName <> "" Then If IsMissing(Directory) Or Directory = False Then File_Exists = (Dir$(sPathName) <> "") Else File_Exists = (Dir$(sPathName, vbDirectory) <> "") End If End If End Function 

这是从“vbatesting如果文件存在”的第二谷歌结果http://vbadud.blogspot.com/2007/04/vba-function-to-check-file-existence.html