使用python调用Excel宏

时间:2019-06-26 13:23:45

标签: python excel vba

我正在尝试编写将在excel工作簿中运行宏的python代码。我知道文件名和vba宏的名称。我不需要将任何信息读取到python文件中,只需执行此功能即可。

我最终希望定期运行此python代码,并希望它在一天内多次调用同一个VBA函数。

import openpyxl


excel_document = openpyxl.load_workbook('python test.xlsm')
print type(excel_document)

1 个答案:

答案 0 :(得分:0)

我在Stackoverflow上找到了此代码。也许对您有帮助。

资源: Running an Excel macro via Python?

import win32com.client

if os.path.exists("excelsheet.xlsm"):
    xl = win32com.client.Dispatch("Excel.Application")
    wb = xl.Workbooks.Open(os.path.abspath("C:\Users\{Username}\Desktop\test.xlsm"), ReadOnly=0)
    wb.Sheets('Sheet1').Select()
    xl.Application.Run("test.xlsm!Module1.macroname")
##    xl.Application.Save() # if you want to save then uncomment this line and change delete the ", ReadOnly=1" part from the open function.
    xl.Application.Quit() # Comment this out if your excel script closes
    del xl```