2010-11-19 17 views
0

我使用DIR打開一個文件:VBA:捕捉文件未發現異常與DIR

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

如果DIR沒有,然後我得到一個異常BAD的文件名或號碼存在;但是,如果目錄存在,那麼這個IF語句工作正常。

question在DIR不存在的情況下,如何處理異常?

+0

什麼是「一些目錄」可能是什麼?儘管使用+連接而不是&,並不會產生所述的錯誤,但上述代碼依然運行。 – Fionnuala 2010-11-19 18:50:25

回答

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

這個怎麼樣?

+0

看起來很完美,你能否也請回答這一個http://stackoverflow.com/questions/4227526/vba-passing-a-variable-into-error-handles – 2010-11-19 17:10:20

+0

當然...我會看看 – thedev 2010-11-19 17:19:58

+0

這個不工作,它返回文件未找到 – 2010-11-19 18:13:08

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