VBA - 找不到文件时的msgbox

时间:2012-08-17 17:52:46

标签: excel vba excel-vba

我想要一个msgbox在找不到文件TestData.xlsx时显示“找不到文件”。感谢

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 个答案:

答案 0 :(得分:9)

在for循环之前检查文件:

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

答案 1 :(得分: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 test if if file exists”http://vbadud.blogspot.com/2007/04/vba-function-to-check-file-existence.html

的第二个google结果

答案 2 :(得分:3)

添加对“Microsoft Scripting Runtime”的引用

Menu Path ReferenceWindow

然后:

Dim fso As New FileSystemObject

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