I\'ve got a macro that I\'d like a bunch of existing spreadsheets to use. The only problem is that there are so many spreadsheets that it would be too time consuming to do i
I'd like to add to this. I was having trouble trying to parse through every .xlsm file in my folder. I figured out how to do it using glob and formatting a with statement inside a for statement. I am new to programming so please excuse me if I am using incorrect terminology. Hope this helps others. Thanks.
import glob
import os, sys
import win32com.client
_file = os.path.abspath(sys.argv[0])
path = os.path.dirname(_file)
pathToMacro = path + r'\macro2.txt'
myMacroName = 'TestMacro'
for fname in glob.glob(path + "\*.xlsm"):
with open (pathToMacro, "r") as myfile:
print('reading macro into string from: ' + str(myfile))
macro=myfile.read()
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = False
workbook = excel.Workbooks.Open(Filename=fname)
excelModule = workbook.VBProject.VBComponents.Add(1)
excelModule.CodeModule.AddFromString(macro)
excel.Application.Run('Module1.CleanDataPivot')
excel.Workbooks(1).Close(SaveChanges=1)
excel.Application.Quit()
del excel
Now I can run one macro through every .xlsm file in my folder without opening up excel.