Run a VBA macro from PowerPoint through C#


A small useful post about Office Automation. Hope it will be helpful for others as well.

In one of the recent situations I had to run a VBA PowerPoint macro from my C# code. You’ll find a great post from Microsoft about it from which I have developed my code.

You first need to instantiate PowerPoint:

using PowerPoint = Microsoft.Office.Interop.PowerPoint;

PowerPoint.Application oPP = new PowerPoint.ApplicationClass();
oPP.DisplayAlerts = Microsoft.Office.Interop.PowerPoint.PpAlertLevel.ppAlertsNone;
oPP.Visible = MsoTriState.msoTrue;

PowerPoint.Presentations oPresSet = oPP.Presentations;
PowerPoint._Presentation _activePres = oPresSet.Open("PowerPoint File Location",
MsoTriState.msoTrue, MsoTriState.msoFalse,
MsoTriState.msoTrue);

Now, you can use the RunMacro method to call the Macro which are written in that PowerPoint file:

object _retobj1 = RunMacro(oPP, new Object[] { "MyMacro1"});
object _retobj2 = RunMacro(oPP, new Object[] { "MyMacro","argument 1"});

If the Macro does not accept any argument then you can use the first one else you can chose the 2nd one.

Here is the run macro method I have used:


public static object RunMacro(object oApp, object[] oRunArgs)
{
try
{
return oApp.GetType().InvokeMember("Run",
System.Reflection.BindingFlags.Default |
System.Reflection.BindingFlags.InvokeMethod,
null, oApp, oRunArgs);

}
catch (Exception _exp)
{
//Log Exception
}

return null;
}

Advertisements