使用 c 将 VB 模块添加到 PowerPoint 演示文稿#

Add a VB module to a PowerPoint Presentation using c#

提问人:Kipp Woodard 提问时间:4/21/2023 更新时间:4/22/2023 访问量:61

问:

使用本文中的示例将 VBA 宏添加到 powerpoint,我正在向 PowerPoint 演示文稿添加 VB 模块(后期绑定)。

它似乎在 VS 调试中成功。我可以看到新模块,带有我给它的名字,行数正确。

但是,当我打开保存的 PowerPoint 文件时,该模块不在 VB 项目中。我的模块发生了什么情况?

        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;
            }
        }

我尝试了上面的代码。该模块似乎已添加。在 PowerPoint 中打开演示文稿时,它不存在。

C# VBA 模块 PowerPoint

评论

5赞 FunThomas 4/21/2023
注入模块后是否以 pptm 格式存储文件?

答:

0赞 Kipp Woodard 4/21/2023 #1

正如 FunThomas评论中所说,有必要将演示文稿保存为 PPTM。