我必须在 excel 文件中运行宏,这可以通过 python win32 完成。但是我有运行宏所需的第三方 excel 加载项。 win32打开的excel没有插件链接。加载项采用 XLA 文件格式。
这是我的代码
new_file_path = path to excel_file.xlsm
xl = win32com.client.Dispatch('Excel.Application')
xl.Visible = True
refprop_path = path to XLA file
xl.Workbooks.Open(refprop_path)
xl.AddIns.Add(refprop_path)
xl.Workbooks.Open(new_file_path)
xl.Application.Run("iter1.xlsm!Sheet1.copy_data")
for i in range(0, 3):
xl.Application.Run("iter1.xlsm!Sheet1.temp_const_gauge")
xl.Application.Run("iter1.xlsm!Sheet1.copy_data")
xl.Application.Save()
xl.Application.Quit()
加载项未添加,出现错误。
xl.AddIns.Add(refprop_path).Installed = True
File "<COMObject <unknown>>", line 3, in Add
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u'Add method of AddIns class failed', u'xlmain11.chm', 0, -2146827284), None)
请您参考如下方法:
我不必明确地写一行来添加插件。我删除了那一行,问题就解决了。
工作代码:
new_file_path = path to excel_file.xlsm
xl = win32com.client.Dispatch('Excel.Application')
xl.Visible = True
refprop_path = path to XLA file
xl.Workbooks.Open(refprop_path)
xl.Workbooks.Open(new_file_path)
xl.Application.Run("iter1.xlsm!Sheet1.copy_data")
for i in range(0, 3):
xl.Application.Run("iter1.xlsm!Sheet1.temp_const_gauge")
xl.Application.Run("iter1.xlsm!Sheet1.copy_data")
xl.Application.Save()
xl.Application.Quit()
XLA文件中的加载项我好像只要在后台保持打开就可以使用了。
