使用 win32com.client 编写并执行 excel VB 宏

Write and execute excel VB macro with win32com.client

我正在尝试编写一个脚本来打开现有的 .xlsx 文件,编写一个 Visual Basic 宏脚本来自动调整注释大小,执行所述宏,然后关闭并保存工作簿。

我对 win32com.client 很不熟悉,经过几个小时的挖掘,我没有找到从 python 编写 VB 宏脚本的好文档。因此,我使用这些线程的反馈拼接了一个脚本:

这里是我想出的代码的粗略表示:

import openpyxl, win32com.client as win32, comtypes, comtypes.client

class report:
    def __init__(self,name,dpath,inputs,**kw):
        self.name=name
        self.dpath=dpath
        #ommited scripts builds excel report with openpyxl, then saves it

        self.xl=win32.gencache.EnsureDispatch('Excel.Application')
        self.xl.Visible=False

        self.report=self.xl.Workbooks.Open(dpath+'\'+self.name+'.xlsx')
        self.report.Worksheets("Audit Assistant Report").Activate()

        self.sheet=self.report.ActiveSheet

        self.xlmodule=self.sheet.VBProject.VBComponents.Add(1)

        self.excelcode="""Sub FitComments()
'Updateby20140325
Dim xComment As Comment
For Each xComment In Application.ActiveSheet.Comments
xComment.Shape.TextFrame.AutoSize = True
Next
End Sub"""

        self.xlmodule.CodeModule.AddFromString(self.excelcode)
        self.report.Run(self.name+'.xlsx!Macro_1')
        self.report.Close(savechanges=True)
        self.xl.Quit()

def main():
    #input definitions omitted
    report("myreport","C:\somepath\",inputs)

if__name__=='__main__':
    main()

当我尝试 运行 脚本时,它会产生以下回溯:

Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\win32com\client\__init__.py", line 473, in __getattr__
    raise AttributeError("'%s' object has no attribute '%s'" % (repr(self), attr))
AttributeError: '<win32com.gen_py.Microsoft Excel 14.0 Object Library._Worksheet instance at 0x229316888>' object has no attribute 'VBProject'

我已尝试更新我的 PyWin32 程序包,并确定这不是问题所在。

脚本中需要更改什么才能使其执行并产生预期效果?

提前感谢您的宝贵时间和意见。

Sheet 对象没有 VBProject 属性。它在工作簿级别,所以使用这个:

self.xlmodule=self.report.VBProject.VBComponents.Add(1)

希望对您有所帮助。