如何解决Python 将宏添加到现有的 XLSM
嗯。我有一个完整的宏 xlsm 数据。我必须向工作簿添加一个 Workbook_Open vba 脚本。 但是对于较低的代码,它只能向模块部分添加代码。我必须将 vba 代码添加到“此工作簿”部分。
嗯。将 vbaProject.bin 转换为 xlsm 数据可能更好。但我认为这仅适用于 xlswriter 库。而且这个库不能将 vba 添加到现有的 xlsm :(
有人可以帮我吗?
# set file paths and macro name accordingly - here we assume that the files are located in the same folder as the Python script
pathToExcelFile = 'Dir/test.xlsx'
pathToMacro = 'Dir/test/macro.txt'
myMacroName = 'UsefulMacro'
# read the textfile holding the excel macro into a string
with open (pathToMacro,"r") as myfile:
print('reading macro into string from: ' + str(myfile))
macro=myfile.read()
print(macro)
# open up an instance of Excel with the win32com driver
excel = win32com.client.Dispatch("Excel.Application")
# do the operation in background without actually opening Excel
excel.Visible = False
# open the excel workbook from the specified file
workbook = excel.Workbooks.Open(Filename=pathToExcelFile)
# insert the macro-string into the excel file
excelModule = workbook.VBProject.VBComponents.Add(1)
excelModule.CodeModule.AddFromString(macro)
# run the macro
#excel.Application.Run(myMacroName)
xlOpenXMLWorkbookMacroEnabled = 52
# save the workbook and close
#excel.Workbooks(1).Close(SaveChanges=1)
excel.Workbooks(1).SaveAs('testneu.xlsm',FileFormat=xlOpenXMLWorkbookMacroEnabled)
#wb.SaveAs(filename,FileFormat=xlOpenXMLWorkbookMacroEnabled)
excel.Application.Quit()
# garbage collection
del excel
解决方法
试试这个代码:
import win32com.client
xl = win32com.client.Dispatch("Excel.Application")
code = 'Private Sub Workbook_Open() \n \
MsgBox "Hello!" \n \
End Sub'
path = r'c:\Users\Alex20\Documents\test.xlsm'
wb = xl.Workbooks.Open(path)
wb.VBProject.VBComponents(1).CodeModule.AddFromString(code)
#xl.Visible = True
wb.Close(True)
xl.Quit()
之前:
之后:
跑步:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。