[英]Error handling with if…then VBA
Is there any way to use if...then for error handling ( without On Error... or GoTo !!!!)? 如果...然后进行错误处理( 没有On Error ...或GoTo !!!!),有什么方法可以使用吗?
I have the below code, but it's stuck at the if statement. 我有以下代码,但是卡在if语句中。
Sub test()
If IsError(Workbooks.Open("C:\Users\Desktop\Test\journals.xlsx")) = True Then
'Do something
End If
End Sub
Thanks! 谢谢!
you could use Dir()
function 您可以使用
Dir()
函数
If Dir("C:\Users\Desktop\Test\journals.xlsx") = "" Then
'do something
Else
Workbooks.Open "C:\Users\Desktop\Test\journals.xlsx"
End If
You can turn off error handling and then check if an error number was generated from the attempt at opening the workbook. 您可以关闭错误处理,然后检查尝试打开工作簿时是否生成了错误号。
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
Edit 1: Since you are already doing so nicely, directly setting it to a wb
object, why not use it's capabilities ? 编辑1:由于您已经做得很好,直接将其设置为
wb
对象,为什么不使用它的功能呢?
If wb Is Nothing Then
The simplest answer is no, it's expected that you'll use On Error in some fashion, either: 最简单的答案是“否”,预计您将以某种方式使用“错误”:
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
or in a traditional error handler: 或在传统的错误处理程序中:
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
However, you can use the FileSystemObject to test if a file exists: 但是,可以使用FileSystemObject来测试文件是否存在:
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
fileExists = fso.fileExists("C:\Users\Desktop\Test\journals.xlsx")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.