Remove Macro from Excel File using C#

Remove Macro from Excel File using C#

Macro:

A pre-recorded or written script (programs) kept within Excel file and stored within Sheet Level Module/Standard Modules/Class Modules. Sometime developer may in need to process a file without these macros as your target system might not supports macros where you are about to store it. This entire scripting environment called VBA, and Operations getting facilitated by VBE (Visual Basic Editor). The entire VBE environment manages VBA project architecture like Modules, Form Interfaces etc.

To manipulate VBA or Macro code we need to use VBE. in DOT NET To Access VBE environment we have to reference Microsoft.VBe.Introp in the project.

Code example:

public static void RemoveMacroFromWorkbook(Microsoft.Office.Interop.Excel.Workbook xlWorkbook)
{
	try
	{
		VBE.VBComponents objComComponents = xlWorkbook.VBProject.VBComponents;
		foreach (VBE.VBComponent component in objComComponents)
		{
			if(component.Type==VBE.vbext_ComponentType.vbext_ct_StdModule || component.Type == VBE.vbext_ComponentType.vbext_ct_ClassModule || component.Type == VBE.vbext_ComponentType.vbext_ct_MSForm || component.Type == VBE.vbext_ComponentType.vbext_ct_ActiveXDesigner)
			{
				objComComponents.Remove(component);
			}
		}
	}
	catch (Exception e)
	{

		throw;
	}
}

The above code will identify VBA modules within workbook and remove them.

Next>>Determine Cell Reference Formula Excel C#

Leave a Reply

Your email address will not be published.