代码之家  ›  专栏  ›  技术社区  ›  Alex Gordon

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

  •  0
  • Alex Gordon  · 技术社区  · 14 年前

    我正在使用DIR打开一个文件:

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

    如果目录不存在,那么我得到一个异常坏的文件名或数字;但是如果目录存在,那么if语句工作得很好。

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

    2 回复  |  直到 14 年前
        1
  •  2
  •   thedev    14 年前
    Public Function IsADirectory(ByVal TheName As String) As Boolean
      If GetAttr(TheName) And vbDirectory Then
        IsADirectory = True
      End If
    End Function
    

    这个怎么样?

        2
  •  0
  •   ForEachLoop    14 年前

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

    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