Search code examples
c#vbamodulepowerpoint

Add a VB module to a PowerPoint Presentation using c#


Using the example in this article Adding a VBA macro to powerpoint I am adding a VB module to a PowerPoint presentation (late bound).

It appears to be successful in VS debug. I can see the new module, with the name I gave it and the line count is correct.

However, when I open the saved PowerPoint file the module is not in the VB project. What is happening to my module?

        private void AddDodecaModuleToPresentation(dynamic presentation)
        {
            try
            {
                dynamic codeModule = GetNewDodecaCodeModule(presentation);

                if (codeModule == null)
                    return;

                dynamic lineNum = codeModule.CountOfLines + 1;

                string codeText = $"Public Sub ListSlideNames(){Environment.NewLine}Dim oSlide As Slide{Environment.NewLine}For Each oSlide In Presentations(1).Slides{Environment.NewLine}Debug.Print \"Slide \" & oSlide.SlideIndex & \":  & oSlide.Name{Environment.NewLine}Next{Environment.NewLine}End Sub";

                codeModule.InsertLines(lineNum, codeText);

                // The module is observable in the watch window in the Presentation at this point.
                presentation.Save();
            }
            catch
            {
                // ignored
            }
        }

        private dynamic GetNewDodecaCodeModule(dynamic presentation)
        {
            try
            {
                dynamic project = presentation.VBProject;
                if (project == null)
                    return null;

                // No action if Dodeca module exists already.
                foreach (dynamic existingModule in project.VBComponents)
                    if (existingModule.Name == "Dodeca")
                        return null;

                dynamic module = project.VBComponents.Add(vbext_ComponentType_vbext_ct_StdModule);
                if (module == null)
                    return null;

                module.Name = "Dodeca";

                return module.CodeModule;
            }
            catch
            {
                return null;
            }
        }

I tried the code above. The module appears to have been added. It is not there when the presentation is opened in PowerPoint.


Solution

  • As FunThomas said in a comment, it is necessary to save the presentation as PPTM.