xlwings:在Python错误发生时终止VBA执行

huangapple go评论98阅读模式
英文:

xlwings: terminate VBA execution upon Python error

问题

你可以在调用Python函数后检查是否发生了错误,并使用VBA的Exit Sub语句来立即终止VBA子程序的执行。以下是示例代码:

Sub YourVBAProcedure()
    ' 调用Python函数
    result = RunPython("your_python_function()")
    
    ' 检查Python函数是否返回了错误信息
    If result = "Error" Then
        MsgBox "Python函数发生了错误"
        Exit Sub ' 立即终止VBA子程序的执行
    End If
    
    ' 继续执行剩余的VBA代码
    ' ...
End Sub

在上述示例中,当RunPython返回一个表示错误的结果时,VBA会显示一个消息框,然后使用Exit Sub语句立即终止子程序的执行。

英文:

I have an Excel VBA subroutine that calls a Python function with the xlwings RunPython command. If the called Python function terminates due to an error, then a pop-up with the Python error traceback appears in Excel. However afterwards Excel happily continues with execution of the remainder of the VBA subroutine.

How can I force the VBA subroutine to terminate immediately after the Python function from RunPython raises an error?

答案1

得分: 0

RunPython在出错时返回-1。因此,解决方案如下:

return_code = RunPython("import hello; hello.world()")
If return_code = -1 Then
    End
End If
英文:

RunPython returns -1 in case of an error. Therefore a solution is:

return_code = RunPython("import hello; hello.world()")
If return_code = -1 Then
    End
End If

huangapple
  • 本文由 发表于 2023年8月9日 15:31:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76865523-2.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定