satya
satya

Reputation: 2607

How to Enable Macro settings thru code?

I have created a Macro in a Powerpoint Presentation using the following code. When running this small piece of code I was getting an exception " programmatic access to visual basic project is not trusted". I know this can be resolved by changing the Trust Center Settings in options. But can anyone help me how I can change these settings thru code. ike any powerpoint interop APIs?? pl suggest.. Thanks in advance.

My sample code:

PowerPoint.Application oPPT = new PowerPoint.Application();
oPPT.Visible = Office.MsoTriState.msoTrue;

//Add New Presentation
PowerPoint.Presentations oPresSet = oPPT.Presentations;
PowerPoint.Presentation oPres = oPresSet.Add(Office.MsoTriState.msoTrue);

//Add Slides to the Presentation
PowerPoint.Slides oSlides = oPres.Slides;
PowerPoint.Slide oSlide = oSlides.Add(1, PowerPoint.PpSlideLayout.ppLayoutTitle);

VBComponent vbc =  oPres.VBProject.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule);
string code = "sub VBAMacro()\r\n" + "ActivePresentation.Close\n" + "End Sub";
vbc.CodeModule.AddFromString(code);

Upvotes: 0

Views: 2009

Answers (1)

John Koerner
John Koerner

Reputation: 38087

In the end, that setting is just stored in a registry key, so you could do something like this, but you will need to run with permissions to access that registry key. I did a basic test and it seemed to work on my machine.

using (var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Office\14.0\PowerPoint\Security",true))
{
    int origVal = (int)key.GetValue("AccessVBOM", 0);
    if (origVal != 1)
        key.SetValue("AccessVBOM", 1);


    PowerPoint.Application oPPT = new PowerPoint.Application();
    oPPT.Visible = Office.MsoTriState.msoTrue;

    //Add New Presentation
    PowerPoint.Presentations oPresSet = oPPT.Presentations;
    PowerPoint.Presentation oPres = oPresSet.Add(Office.MsoTriState.msoTrue);

    //Add Slides to the Presentation
    PowerPoint.Slides oSlides = oPres.Slides;
    PowerPoint.Slide oSlide = oSlides.Add(1, PowerPoint.PpSlideLayout.ppLayoutTitle);

    VBComponent vbc = oPres.VBProject.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule);
    string code = "sub VBAMacro()\r\n" + "ActivePresentation.Close\n" + "End Sub";
    vbc.CodeModule.AddFromString(code);

    if (origVal != 1)
    {
        key.SetValue("AccessVBOM", origVal);
    }

    key.Close();
}

Upvotes: 2

Related Questions