Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add, Extract, Remove VBA Macros in PowerPoint using C#
// Load presentation
using (Presentation presentation = new Presentation("presentation.pptm"))
{
// Create new VBA Project
presentation.VbaProject = new VbaProject();
// Add empty module to the VBA project
IVbaModule module = presentation.VbaProject.Modules.AddEmptyModule("Module");
// Set module's source code
module.SourceCode = @"Sub Test(oShape As Shape) MsgBox ""Test"" End Sub";
// Create reference to <stdole>
VbaReferenceOleTypeLib stdoleReference =
new VbaReferenceOleTypeLib("stdole", "*\\G{00020430-0000-0000-C000-000000000046}#2.0#0#C:\\Windows\\system32\\stdole2.tlb#OLE Automation");
// Create reference to Office
VbaReferenceOleTypeLib officeReference =
new VbaReferenceOleTypeLib("Office", "*\\G{2DF8D04C-5BFA-101B-BDE5-00AA0044DE52}#2.0#0#C:\\Program Files\\Common Files\\Microsoft Shared\\OFFICE14\\MSO.DLL#Microsoft Office 14.0 Object Library");
// Add references to the VBA project
presentation.VbaProject.References.Add(stdoleReference);
presentation.VbaProject.References.Add(officeReference);
// Save Presentation
presentation.Save("AddVBAMacros.pptm", SaveFormat.Pptm);
}
// Load presentation
using (Presentation pres = new Presentation("presentation.pptm"))
{
if (pres.VbaProject != null) // check if Presentation contains VBA Project
{
foreach (IVbaModule module in pres.VbaProject.Modules)
{
Console.WriteLine(module.Name);
Console.WriteLine(module.SourceCode);
}
}
}
// Load presentation
using (Presentation presentation = new Presentation("Presentation.pptm"))
{
// Remove the VBA module
presentation.VbaProject.Modules.Remove(presentation.VbaProject.Modules[0]);
// Save presentation
presentation.Save("RemovedVBAMacros.pptm", SaveFormat.Pptm);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment