1

当找不到文件 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
4

3 回答 3

10

在 for 循环之前检查文件:

If Dir$("C:\Documents\TestData.xlsx") = "" Then
    MsgBox "File not found"
    Exit Sub
End If
于 2012-08-17T18:07:08.827 回答
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

于 2012-08-17T18:02:42.903 回答
3

添加对“Microsoft Scripting Runtime”的引用

菜单路径 参考窗口

接着:

Dim fso As New FileSystemObject

If Not fso.FileExists("C:\Documents\TestData.xlsx") Then MsgBox "File Not Found."
于 2012-08-17T18:16:17.187 回答