我是一名Python初学者程序员,但最近我在access和excel中使用VBA进行了一些编码。
我正在编写一个代码,该代码从两个不同的查询(从访问 Excel 工作簿)导出一些数据。然后,我继续从 Excel 中对数据进行更多处理,以便进行一些销售分析。
问题是,有时,查询之一(或两者)可能为空,这会引发
error '3021'
我想做的是,如果
error '3021'
发生在特定 block 中,跳转到特定行并继续执行。
在 python 中,我会放置该代码块 - 我知道可以提高
error '3021'
在“try”内避免执行
#code here
Try:
#code that may raise error
Except Exception as '3021':
pass
#code here....
在 VBA 中我能够处理
error '3021'
但不是我想要的。一旦我“管理”了
error '3021'
如果代码的其余部分中出现另一个错误,则最后一个错误处理程序始终处于事件状态(隐藏我想引发以进行调试的其他错误引发。代码摘录如下:
On Error GoTo Err1Handler
'here starts the code that may raise the error '3021'
consulta16.MoveFirst
Datos16.Range("A2").CopyFromRecordset consulta16
With APIExcel.ActiveSheet.Cells
.Select
.EntireColumn.AutoFit
.Range("A1").Select
End With
'From here I know there wont be an error '3021'
NoData16:
columnas = consulta17.Fields.Count
For i = 0 To columnas - 1
Datos17.Cells(1, i + 1) = consulta17.Fields(i).Name
Next i
'Now comes the second query that may raise same
error '3021'
所以我又犯了一个错误异常
On Error GoTo Err2Handler
consulta17.MoveFirst
Datos17.Range("A2").CopyFromRecordset consulta17
With APIExcel.ActiveSheet.Cells
.Select
.EntireColumn.AutoFit
.Range("A1").Select
End With
'#more code.......
Err1Handler:
If Err.Number = 3021 Then
'MsgBox ("Sin datos del 16")
Resume NoData16
End If
Err2Handler:
If Err.Number = 3021 Then
'MsgBox ("Sin datos del 17")
Resume NoData17
End If
我读到here 本文档介绍了 Vba 中的错误处理,但我不知道如何在不影响整个脚本的情况下处理特定错误。我想我正在尝试在 python 中进行编码时面对 vba 错误处理...如果有人可以帮助我理解如何在错误处理程序中隔离代码块而不影响整个脚本(Try/Catch/Finally 方式? )
最佳答案
我会这样做:
选项显式
Public Sub TestMe()
Dim a As Long
Dim b As Long
On Error GoTo TestMe_Error
a = 1: b = 0
Debug.Print a / b 'Error 11
Debug.Print "Some more stuff..."
Debug.Print a / b 'Error 11
Debug.Print "Some other stuff..."
a = 0
Debug.Print a / b 'Error 6
On Error GoTo 0
Exit Sub
TestMe_Error:
If Err.Number = 11 Then
Resume Next
Else
MsgBox Err.Number & " " & Err.Description
End If
End Sub
因此,如果您查找错误 11,它将忽略它并继续,并且将捕获所有其他错误(例如捕获错误 6)。
这是如何找到导致错误的行:
Public Sub TestMe()
On Error GoTo TestMe_Error
Debug.Print 3 / 4
Debug.Print 4 / 0
Debug.Print 6 / 1
On Error GoTo 0
Exit Sub
TestMe_Error:
Stop
Resume
End Sub
代码在 Stop
行停止后,如果按两次 F8,您将转到错误行。
关于vba - 错误处理 VBA(如果 Err raise 则跳过此 block ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47905520/