我将 VBA 与 Python 结合使用。
我导入了模块 OS,并使用 excel - openpyxl。当它迭代从 Excel 运行 VBA 宏的函数时会出现问题。
import random
from openpyxl import load_workbook
import os, os.path, win32com.client
wbi = load_workbook('Input.xlsm')
wsi = wbi.get_active_sheet()
wbo = load_workbook('Output.xlsx')
wso = wbo.get_active_sheet()
def run_macro(fName, macName, path=os.getcwd()):
"""
pre: fName is the name of a valid Excel file with macro macName
post: fName!macName is run, fName saved and closed
"""
fName = os.path.join(path, fName)
xlApp = win32com.client.Dispatch("Excel.Application")
fTest = xlApp.Workbooks.Open(fName)
macName = fTest.Name + '!' + macName
xlApp.Run(macName)
fTest.Close(1)
xlApp.Quit()
xlApp = None
def IBP():
ibp = wsi.cell('G12')
ibpv = random.randint(0,45)
ibp.value = ibpv
return ibp.value
def BP10():
bp10 = wsi.cell('G13')
bpv10 = random.randint(30,50)
bp10.value = bpv10
return bp10.value
for n in range(6):
IBP()
print IBP()
BP10()
run_macro('Input.xlsm','macro1')
wbo.save('Output.xlsx')
我认为错误在于run_macro('Input.xlsm','macro1')
- 它无法迭代。
输出:
Qt: Untested Windows version 6.2 detected!
35
4
Traceback (most recent call last):
File "C:\Users\User\Desktop\Python Exp\Pr 1.py", line 77, in <module>
run_macro('Input.xlsm','macro1')
File "C:\Users\User\Desktop\Python Exp\Pr 1.py", line 18, in run_macro
fTest = xlApp.Workbooks.Open(fName)
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 522, in __getattr__
raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: Excel.Application.Workbooks
我究竟做错了什么?