英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论