我尝试使用 python 和 win32com 库应用 VBA 宏,想法是创建一个固定的 excel 文件,存储一个宏然后运行它。我从这里得到了这个想法:https ://redoakstrategic.com/pythonexcelmacro/
当脚本必须使用 xlsm 文件并使用 Application.Run() 运行宏时,就会出现问题。我的代码是:
import pandas as pd
import win32com.client
import os
#creating the dataframe
df = df1=pd.read_excel ("normal_excel_file.xlsx", index_col=0)
filename = "normal_excel_file.xlsx"
writer = pd.ExcelWriter(filename, engine='xlsxwriter')
df.to_excel(writer, sheet_name='data', index=False)
#copiying and renaming the file to xlsm
shutil.copy("normal_excel_file.xlsx", "(1)normal_excel_file.xlsx")
os.rename("(1)normal_excel_file.xlsx", "macros_excel_file.xlsm")
#adding the macro to the workbook
filename_macro = r"C:\Users\John\Desktop\Python_scripts\Running VBA Macro\macros_excel_file.xlsm"
workbook = writer.book
workbook.filename = filename_macro
workbook.add_vba_project('vbaProject.bin')
writer.save()
和冲突的部分:
if os.path.exists(filename_macro):
xl = win32com.client.Dispatch('Excel.Application')
xl.Workbooks.Open(Filename = filename_macro, ReadOnly=1)
#assuming that there is only one macro, and is stored as "ThisWorkbook.Macro1" in the file
xl.Application.Run("ThisWorkbook.Macro1") #I also try using only "Macro1" and the whole path of the file
xl.Application.Quit()
del xl
我得到下一个错误。首先是错误信息:
com_error: (-2147352567, 'An exception occurred.', (0, 'Microsoft Excel', 'The "ThisWorkbook.Macro1" macro cannot be executed. The macro may not be available in this book or all of them may have been disabled. the macros. ',' xlmain11.chm ', 0, -2146827284), None)
我转到 Microsoft Office 中的信任中心,并允许所有宏类型(https://support.office.com/en-us/article/enable-or-disable-macros-in-office-files-12b036fd-d140 -4e74-b45e-16fed1a7e5c6?ui=en-US&rs=en-US&ad=US )。但是错误继续发生
如果有人知道如何解决它会很棒
喵喵时光机
相关分类