VbaModuleCollection.Add

Add(Worksheet)

Adds module for a worksheet.

public int Add(Worksheet sheet)
ParameterTypeDescription
sheetWorksheetThe worksheet

Examples

using System;
using Aspose.Cells;

namespace AsposeCellsExamples
{
    public class VbaModuleCollectionMethodAddWithWorksheetDemo
    {
        public static void Run()
        {
            // Create a new workbook
            Workbook workbook = new Workbook();
            
            // Access the first worksheet
            Worksheet worksheet = workbook.Worksheets[0];
            
            // Add a VBA module associated with the worksheet
            int moduleIndex = workbook.VbaProject.Modules.Add(worksheet);
            
            // Add some VBA code to the module
            string vbaCode = "Sub Test()\n    MsgBox \"Hello from VBA!\"\nEnd Sub";
            workbook.VbaProject.Modules[moduleIndex].Codes = vbaCode;
            
            // Save the workbook with VBA project
            workbook.Save("output.xlsm", SaveFormat.Xlsm);
        }
    }
}

See Also


Add(VbaModuleType, string)

Adds module.

public int Add(VbaModuleType type, string name)
ParameterTypeDescription
typeVbaModuleTypeThe type of module.
nameStringThe name of module.

Examples

using System;
using Aspose.Cells;
using Aspose.Cells.Vba;

namespace AsposeCellsExamples
{
    public class VbaModuleCollectionMethodAddWithVbaModuleTypeStringDemo
    {
        public static void Run()
        {
            Workbook workbook = new Workbook();
            VbaProject vbaProject = workbook.VbaProject;

            int index = vbaProject.Modules.Add(VbaModuleType.Class, "TestModule");
            VbaModule module = vbaProject.Modules[index];
            module.Codes = "Sub Test()\r\nMsgBox \"Hello World\"\r\nEnd Sub";

            workbook.Save("VbaModuleAddExample.xlsm");
        }
    }
}

See Also