It seems win32api should be able to do this given the answer here and [.
I would like to remove all modules from an excel workbook (.xls) using python
Consider using the VBComponents collection available in the COM interface accessible with Python's win23com.client
module. However, inside the particular workbook you need to first grant programmatic access to the VBA object library.
Also, you will need to conditionally set the type as this procedure cannot delete object modules including Sheets (Type = 100
) and Workbooks (Type = 100
). Only Standard Modules (Type = 1
), Class Modules (Type = 2
), UserForms (Type= 3
), and other inserted components can be removed. Of course you can iterate through defined list of modules to remove. Try/Except
statement is used to effectively close out the Excel.Application process whether script fails or not.
import win32com.client
# OPEN EXCEL APP AND WORKBOOK
xlApp = win32com.client.Dispatch("Excel.Application")
xlwb = xlApp.Workbooks.Open("C:\\Path\\To\\Workbook.xlsm")
# ITERATE THROUGH EACH VB COMPONENT (CLASS MODULE, STANDARD MODULE, USER FORMS)
try:
for i in xlwb.VBProject.VBComponents:
xlmodule = xlwb.VBProject.VBComponents(i.Name)
if xlmodule.Type in [1, 2, 3]:
xlwb.VBProject.VBComponents.Remove(xlmodule)
except Exception as e:
print(e)
finally:
# CLOSE AND SAVE AND UNINITIALIZE APP
xlwb.Close(True)
xlApp.Quit
xlApp = None
Actually simply reading in the file with xlrd
, copying with xlutils
, and spitting it out with xlwt
will remove the VBA (and other stuff):
import xlrd, xlwt
from xlutils.copy import copy as xl_copy
rb = xlrd.open_workbook('/path/to/fin.xls')
wb = xl_copy(rb)
wb.save('/path/to/fou.xls')