2017-01-03 44 views
0

有没有什么方法可以使用if ...然后用于错误处理(没有On Error ...或GoTo !!!!)?错误处理if ...然后VBA

我有下面的代码,但它卡在if语句。

Sub test() 

      If IsError(Workbooks.Open("C:\Users\Desktop\Test\journals.xlsx")) = True Then 

       'Do something 

      End If 

    End Sub 

谢谢!

+0

的[好的模式对于VBA错误处理(可能的复制http://stackoverflow.com/questions/1038006/good-patterns- for-vba-error-handling) – vacip

+0

我想在没有On Error语句的情况下解决它。 – Vinnie

+0

使用On Error语句完成VBA中的错误处理。期。在某些情况下,您可以找到问题特定的解决方案。也许你需要更改标题,因为它是误导性的;这不是错误处理,这是检查是否存在文件。 (哪个问题在这里也有10000个答案......) – vacip

回答

4

你可以使用Dir()功能

If Dir("C:\Users\Desktop\Test\journals.xlsx") = "" Then 
    'do something 
Else 
    Workbooks.Open "C:\Users\Desktop\Test\journals.xlsx" 
End If 
+0

这是完美的,谢谢! – Vinnie

+0

不客气。然后,您可能想要将答案标记为已接受。谢谢! – user3598756

3

您可以关闭错误处理,然后检查是否从尝试打开工作簿时生成错误编号。

Dim wb As Workbook 

On Error Resume Next 

Set wb = Workbooks.Open("C:\Users\Desktop\Test\journals.xlsx") 

If Err.Number > 0 Then 

    '' there was an error with opening the workbook 

End If 

On Error GoTo 0 

编辑1:既然你已经这样做很好,它直接设置为wb对象,为什么不使用它的功能?

If wb Is Nothing Then 
+1

允许我提供替代方案, –

2

最简单的答案是否定的,它的预期,你会以某种方式使用上的错误,或者:

On error resume next 
Workbooks.Open("C:\Users\Desktop\Test\journals.xlsx") 
If Err.Number <> 0 then 
' the workbook is not at that location 
Err.Clear 
On Error Goto 0 
End If 

或在传统错误处理程序:

errhandler: 

If Err.Number <> 0 then 
    If Err.Number = 1004 Then 
     ' the workbook is not at that location, do something about it, then resume next 
    End If 
End If 

但是,您可以使用FileSystemObject测试文件是否存在:

Dim fso As Object 

Set fso = CreateObject("Scripting.FileSystemObject") 
fileExists = fso.fileExists("C:\Users\Desktop\Test\journals.xlsx")