【问题标题】:vba: catching a file not found exception with DIRvba:使用 DIR 捕获文件未找到异常
【发布时间】:2010-11-19 16:58:16
【问题描述】:

我正在使用 DIR 打开文件:

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

如果 DIR 不存在,那么我会收到异常错误的文件名或编号;但是,如果目录存在,则此 IF 语句可以正常工作。

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

【问题讨论】:

  • “某些目录”可能是什么?上述代码按原样运行,尽管使用 + 而不是 & 进行连接,但不会产生所述错误。

标签: excel vba


【解决方案1】:
Public Function IsADirectory(ByVal TheName As String) As Boolean
  If GetAttr(TheName) And vbDirectory Then
    IsADirectory = True
  End If
End Function

这个怎么样?

【讨论】:

【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 2010-12-05
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    相关资源
    最近更新 更多