调试

由于 xlwings 可以在任何 Python 环境中运行,因此您可以使用您喜欢的方式进行调试。

  • RunPython当通过调用 Python 时RunPython,您可以设置一个mock_caller,以便轻松地在从 Excel 和 Python 调用该函数之间切换。

  • 用户定义函数(UDFs)对于用户定义函数(UDF)的调试,xlwings 提供了一个方便的调试服务器

首先,Excel 将在消息框中显示 Python 错误:

_images/debugging_error.png

注意

在 Mac 上,如果模块/包的importxlwings导入之前失败,则不会显示弹出窗口,并且状态栏也不会重置。但是,错误仍会记录在日志文件中 (/Users/<User>/Library/Containers/com.microsoft.Excel/Data/xlwings.log)。

RunPython

请考虑以下 Python 源代码的示例代码my_module.py:

# my_module.py
import os
import xlwings as xw

def my_macro():
    wb = xw.Book.caller()
    wb.sheets[0]['A1'].value = 1

if __name__ == '__main__':
    # Expects the Excel file next to this source file, adjust accordingly.
    xw.Book('myfile.xlsm').set_mock_caller()
    my_macro()

my_macro()现在可以从 Python 中轻松运行以进行调试,并通过RunPython从 Excel 运行,而无需更改源代码:

Sub my_macro()
    RunPython "import my_module; my_module.my_macro()"
End Sub

UDF 调试服务器

仅限 Windows:要调试 UDF,请在Debug UDFs的顶部检查插件与设置,即 xlwings VBA 模块的顶部。然后,在您的 Python 源文件末尾添加以下几行并运行它。根据您使用的 IDE,可能需要以“调试”模式运行代码(例如,如果您使用的是 PyCharm 或 PyDev):

if __name__ == '__main__':
    xw.serve()

当您重新计算工作表时 (Ctrl-Alt-F9),代码将在断点处停止或输出任何您可能有的打印调用。

下图显示了代码在 PyCharm 社区版中的断点处停止的情况:

_images/udf_debugging.png

注意

从命令提示符运行调试服务器时,目前没有优雅的方法终止它,但关闭命令提示符将结束其运行。