使用Python将macros注入电子表格

我有一个macros,我想要一堆现有的电子表格使用。 唯一的问题是有太多的电子表格,手工操作太耗时了!

我写了一个Python脚本来使用pyWin32来访问所需的文件,但我似乎无法find一种方法来使用它来添加macros。

一个类似的问题给了这个答案(这不是Python,但它看起来仍然使用COM),但我的COM对象似乎并没有一个名为VBProject的成员:

Set objExcel = CreateObject("Excel.Application") objExcel.Visible = True objExcel.DisplayAlerts = False Set objWorkbook = objExcel.Workbooks.Open("C:\scripts\test.xls") Set xlmodule = objworkbook.VBProject.VBComponents.Add(1) strCode = _ "sub test()" & vbCr & _ " msgbox ""Inside the macro"" " & vbCr & _ "end sub" xlmodule.CodeModule.AddFromString strCode objWorkbook.SaveAs "c:\scripts\test.xls" objExcel.Quit 

编辑:链接到类似的问题引用: 注入并执行Excel VBA代码到从外部来源收到的电子表格

我也忘记提到,虽然这不是Python,但我希望类似的对象成员将通过COM对象提供给我。

这是转换的代码。 您可以使用win32com或comtypes软件包。

 import os import sys # Import System libraries import glob import random import re sys.coinit_flags = 0 # comtypes.COINIT_MULTITHREADED # USE COMTYPES OR WIN32COM #import comtypes #from comtypes.client import CreateObject # USE COMTYPES OR WIN32COM import win32com from win32com.client import Dispatch scripts_dir = "C:\\scripts" conv_scripts_dir = "C:\\converted_scripts" strcode = \ ''' sub test() msgbox "Inside the macro" end sub ''' #com_instance = CreateObject("Excel.Application", dynamic = True) # USING COMTYPES com_instance = Dispatch("Excel.Application") # USING WIN32COM com_instance.Visible = True com_instance.DisplayAlerts = False for script_file in glob.glob(os.path.join(scripts_dir, "*.xls")): print "Processing: %s" % script_file (file_path, file_name) = os.path.split(script_file) objworkbook = com_instance.Workbooks.Open(script_file) xlmodule = objworkbook.VBProject.VBComponents.Add(1) xlmodule.CodeModule.AddFromString(strcode.strip()) objworkbook.SaveAs(os.path.join(conv_scripts_dir, file_name)) com_instance.Quit() 

正如我也努力争取这一点,我将提供另一个应用于Excel xlsmxlsm格式的例子。 上面提供的例子没有什么太大的区别,没有循环遍历不同的文件和更多的注释,只是简单一点。 此外,macros的源代码是从文本文件加载的,而不是在Python脚本中进行硬编码。

请记住将脚本顶部的文件path调整为您的需要。

此外,请记住,Excel 2007/2010/2013仅允许以xlsm格式存储具有macros的工作簿,而不是xlsx 。 将macros插入到xlsx文件时,系统会提示您将其保存为其他格式,否则macros将不会包含在文件中。

最后但并非最不重要的一点,请检查Excel的应用程序外部执行VBA代码的选项是否被激活(默认情况下出于安全原因而被禁用),否则您将收到错误消息。 为此,请打开Excel并转至

文件 – >选项 – >信任中心 – >信任中心设置 – >macros设置 – >激活对Trust access to the VBA project object model标记。

 # get directory where the script is located _file = os.path.abspath(sys.argv[0]) path = os.path.dirname(_file) # set file paths and macro name accordingly - here we assume that the files are located in the same folder as the Python script pathToExcelFile = path + '/myExcelFile.xlsm' pathToMacro = path + '/myMacro.txt' myMacroName = 'UsefulMacro' # necessary imports import os, sys import win32com.client # 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() # 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) # save the workbook and close excel.Workbooks(1).Close(SaveChanges=1) excel.Application.Quit() # garbage collection del excel