【问题标题】:Check for compilation error in Excel via COM通过 COM 检查 Excel 中的编译错误
【发布时间】:2021-08-09 21:36:58
【问题描述】:

我已连接到 Excel 应用程序,可以像这样使用 win32com 从我的 Python 代码执行“调试”->“编译 VBAProject”(灵感来自 here 的代码):

from win32com import client

def compile(self):
    self.__excel = client.GetActiveObject("Excel.Application")
    compile_button = self.__excel.VBE.CommandBars.FindControl(1, 578)
    compile_button.Execute()

如果 Excel VBA 代码中存在编译错误,我会在 Excel 中收到一条弹出消息,告诉我该错误很好。

现在我想从 Python 代码中检查是否存在编译错误,如果存在则引发异常。我不一定需要编译错误成为异常的一部分,但如果可能的话,我当然也很乐意接受。
这可以通过某种方式完成吗?
我一直在尝试编译之前和之后的各种窗口计数等,但到目前为止还没有找到任何表明存在弹出或编译错误的对象的属性。

【问题讨论】:

    标签: python-3.x excel


    【解决方案1】:

    好的,我找到了一个有点丑陋但可行的方法 - 我想为其他有同样问题的人记录一下: 您需要将一个代码文件导入到打开的 Excel 文件中,该文件(至少)定义了一个函数。然后,您可以从 Python 代码中调用此函数并捕获任何异常。如果出现异常,您的代码(包括导入的文件)没有编译,如果没有,则编译通过。

    这是我的代码:
    compile_code.bas

    Public Sub compileCode()
        ' doesn't need to do anything, it just needs to be available!
    End Sub
    

    Python 文件

    from win32com import client
    
    def compile(self) -> bool:
        self.__excel = client.GetActiveObject("Excel.Application")
        self.__book = self.__excel.ActiveWorkbook
        self.__book.VBProject.VBComponents.Import(<Path_to_compile_code.bas>)
        try:
            self.__excel.Application.Run("compileCode")
            # if you reach here the code compiled
            return True
        except Exception:
            return False
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      • 2016-03-20
      • 1970-01-01
      • 1970-01-01
      • 2016-07-28
      相关资源
      最近更新 更多