2012-08-17 47 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