Adding VBA Module
Overview
In Microsoft Project (MPP/XML) files, VBA modules allow you to store macros that automate project management tasks. With Aspose.Tasks for .NET, you can add new procedural or class modules into an existing VBA project. This feature is available starting from version 25.6.
Adding a New VBA Module
The example below shows how to add a new procedural module and assign source code to it. Before running this code, ensure the project already contains VBA modules. Otherwise, an exception will be thrown.
1 Project project = new Project("FileWithVbaProject.mpp");
2
3 if (project.VbaProject.Modules.Count == 0)
4 {
5 throw new InvalidOperationException("Project should contain VBA modules");
6 }
7
8 VbaModule newModule = VbaModule.CreateProceduralModule("TestModule10");
9 newModule.SourceCode = @"Sub TestMacro()
10 MsgBox ""This is a test macro.""
11 End Sub";
12
13 project.VbaProject.Modules.Add(newModule);
14
15 // WriteVba flag should be specified in order to apply changes to MPP file.
16 project.Save("output.mpp", new MPPSaveOptions { WriteVba = true });
This code creates a new VBA module named TestModule10
with a simple macro that shows a message box. To save the module correctly, you must enable the WriteVba
flag in the MPPSaveOptions
.
FAQ
Q: Can I add VBA modules to a project without an existing VBA project?
- No. The target Microsoft Project file must already contain a VBA project with at least one module.
Q: Which types of VBA modules can I add?
- You can add both procedural and class modules.
Conclusion
Adding VBA modules with Aspose.Tasks for .NET provides developers with automation capabilities directly inside Microsoft Project files. This helps extend project functionality with custom macros for repetitive or complex operations.