I am writing a script which opens an excel sheet and enters some data and runs a VBA macro.
import os
import win32com.client
import glob
xl=win32com.client.Dispatch("Excel.Application")
working_dir = os.getcwd()
path = os.path.join(working_dir, 'folder')
file_list = glob.glob(path + '/*.xls*')
for file in file_list:
file_name = str(file)
wb = xl.Workbooks.Open(file_name)
wb.Worksheets("sheet1").Activate()
ws = wb.Activesheet.Name
ws1 = wb.Worksheets(ws)
ws1.Range("E5").FormulaR1C1 = "add_text_here"
xl.Goto(ws1.Range('E5'))
xl.Run("excel_sheet.xls!macro")
wb.Close(SaveChanges=True)
xl.Quit()
I am able to run this script properly. The problem I get is, when I change the run macro to read from a variable like below.
xl.Run(file_name+"!macro") # here I changed file name to a variable
I get
The macro may not be available in this workbook or all macros may be disabled.", 'xlmain11.chm', 0, -2146827284), None)
error.
I really need to do this because I dont want to give the Excel file name hard coded and this Excel file may change. Please help me.