vba:使用DIR捕获文件未找到的异常

时间:2010-11-19 16:58:16

标签: excel vba

我正在使用DIR打开文件:

If Dir("some dir" + "some file", vbNormal) <> "" The
End If

如果DIR不存在,那么我得到一个例外BAD文件名或号码;但是如果dir存在,则此IF语句可以正常工作。

问题在DIR不存在的情况下如何处理异常?

2 个答案:

答案 0 :(得分:2)

Public Function IsADirectory(ByVal TheName As String) As Boolean
  If GetAttr(TheName) And vbDirectory Then
    IsADirectory = True
  End If
End Function

怎么样?

答案 1 :(得分:0)

以下代码处理目标不存在的情况:

Public Function IsADirectory(ByVal TheName As String) As Boolean
    On Error Resume Next
    Dim theResult As Boolean
    theResult = GetAttr(TheName) And vbDirectory
    If Err.Number = 0 Then
        IsADirectory = theResult
    Else
        MsgBox "The target is not found."
    End If
End Function
相关问题