我正在尝试编写一个脚本来打开现有的 .xlsx 文件,编写 Visual Basic 宏脚本来自动调整注释大小,执行所述宏,然后关闭并保存工作簿。
我对 win32com.client 很不熟悉,经过几个小时的挖掘,我没有找到从 python 编写 VB 宏脚本的良好文档。因此,我使用这些线程的反馈拼接了一个脚本:
https://stackoverflow.com/a/19506287/7547876
https://stackoverflow.com/a/2141981/7547876
这是我提出的代码的粗略表示:
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)
希望有帮助。
关于python-2.7 - 使用 win32com.client 编写并执行 Excel VBA 宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43194073/