Alex Gordon
Alex Gordon

Reputation: 60751

vba: catching a file not found exception with DIR

i am using DIR to open a file:

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

if the DIR does not exist then i get an exception BAD filename or number; However if the dir exists then this IF statement works fine.

question how do exception handle in a case where the DIR does not exist?

Upvotes: 0

Views: 4686

Answers (2)

ForEachLoop
ForEachLoop

Reputation: 2586

The following code handles the case of the target not existing:

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

Upvotes: 0

thedev
thedev

Reputation: 2906

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

how about this ?

Upvotes: 2

Related Questions