2012-08-17 46 views
0

我想msgbox显示“未找到文件”,当找不到文件TestData.xlsx。谢谢VBA - 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 

回答

3

这将工作。

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 

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

8

您的for循环之前执行该文件的检查:

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

它的工作表示感谢。 – user1442459 2012-08-17 18:16:09

+0

+1,最简单的方法! – Cylian 2012-08-18 05:58:40

3

增加提及“ Microsoft脚本运行时“

Menu Path ReferenceWindow

然后:

Dim fso As New FileSystemObject 

If Not fso.FileExists("C:\Documents\TestData.xlsx") Then MsgBox "File Not Found." 
+0

为什么要调用另一个DLL?如果任务可以使用''FileLen''或''Dir''内置函数完成? – Cylian 2012-08-18 05:58:10

+1

我猜这是首选,但我发现'FileSystemObject'是一个非常方便的工具,所以我最终将它用于所有与文件相关的任务。代码也更具自描述性:'Dir $'与'.FileExists',哪一个更像是你检查文件的存在? :) – 2012-08-18 14:31:49

+0

迟到的回应,但+1,您的评论。虽然个人而言,如果我使用外部资源,我更喜欢使用后缀绑定,因为这些事情经常在办公室中传递,而且由于拥有较旧版本的dll的人而被烧毁太多次,因此无法找到引用等。设置fs = CreateObject(“Scripting.FileSystemObject”)' – 2015-08-20 13:32:06