【问题标题】:Error handling with if...then VBA使用 if...then VBA 处理错误
【发布时间】:2017-01-03 11:14:06
【问题描述】:

有什么方法可以使用 if...then 进行错误处理(没有 On Error... 或 GoTo!!!!)?

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

Sub test()

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

                'Do something

            End If

  End Sub

谢谢!

【问题讨论】:

  • 我想在没有 On Error 语句的情况下解决它。
  • VBA 中的错误处理是通过 On Error 语句完成的。时期。在某些情况下,您可以找到特定问题的解决方案。也许您需要更改标题,因为它具有误导性;这不是错误处理,这是检查文件是否存在。 (这个问题在 SO 上也有 10000 个答案...)
  • 所以现在它是这个的副本:stackoverflow.com/questions/11573914/…
  • 快速回答是否定的,没有一般替代 On Error 语句(不幸的是)。 IsError 是一个 Excel 函数,用于检查单元格值之间的错误值。也见这里:stackoverflow.com/questions/18562252/if-iserror-in-vba

标签: vba excel


【解决方案1】:

你可以使用Dir()函数

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

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

    • 请允许我提供一个替代方案,
    【解决方案3】:

    最简单的答案是否定的,预计您会以某种方式使用 On Error:

    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")
    

    【讨论】:

      猜你喜欢
      • 2020-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-17
      • 2020-03-15
      • 1970-01-01
      相关资源
      最近更新 更多