【问题标题】:How to get rid of the com_error when running MS-word macro with python?使用python运行MS-word宏时如何摆脱com_error?
【发布时间】:2021-05-11 20:37:20
【问题描述】:

我正在尝试使用 python 运行 MS-word VBA 宏,但我不断收到错误消息。

import win32com.client as win32

WrdApp = win32.GetActiveObject("Word.Application")

#Call current file
WrdDoc = WrdApp.ActiveDocument

#Insert Caption
WrdApp.Selection.InsertCaption(Label='number')
#^This line gives the error

错误信息

com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Word', 'Command failed', 'wdmain11.chm', 36966, -2146824090), None)

任何熟悉 Python 和 MS-word 宏的人都可以告诉我为什么会出现这个错误?

【问题讨论】:

    标签: python ms-word macros win32com


    【解决方案1】:

    如果你想在Label中使用除'Equation'、'Figure'、'Table'或WdCaptionLabelID之外的其他标签,你必须定义一个新的(见https://docs.microsoft.com/en-us/office/vba/api/word.selection.insertcaptionhttps://docs.microsoft.com/en-us/office/vba/api/word.captionlabels) :

    import win32com.client as win32
    
    WrdApp = win32.GetActiveObject("Word.Application")
    
    # Call current file
    WrdDoc = WrdApp.ActiveDocument
    
    cLabel = "number"
    # define new label
    WrdApp.CaptionLabels.Add(Name=cLabel)
    # Insert Caption
    WrdApp.Selection.InsertCaption(Label=cLabel)
    # no error
    

    【讨论】:

      猜你喜欢
      • 2019-03-14
      • 2011-01-29
      • 1970-01-01
      • 2012-02-28
      • 1970-01-01
      • 1970-01-01
      • 2011-12-03
      • 1970-01-01
      • 2021-12-15
      相关资源
      最近更新 更多