将 VBA 宏 UserForm DesignerStorage 从模板复制到目标工作簿

可能的使用场景

Aspose.Cells 允许您将 VBA 项目从一个 Excel 文件复制到另一个 Excel 文件。 VBA 项目由各种类型的模块组成,即文档、过程、设计器等。所有模块都可以用简单的代码复制,但对于设计器模块,有一些额外的数据需要访问或复制,称为设计器存储。以下两种方法处理 Designer Storage。

将 VBA 宏 UserForm DesignerStorage 从模板复制到目标工作簿

请参阅以下示例代码。它将 VBA 项目从模板 Excel 文件到一个空的工作簿中并将其另存为输出Excel文件.如果您打开模板 Excel 文件中的 VBA 项目,您将看到如下所示的用户窗体。用户表单由 Designer Storage 组成,因此将使用VbaModuleCollection.GetDesignerStorage()VbaModuleCollection.AddDesignerStorage()方法。

todo:image_alt_text

以下屏幕截图显示了输出 Excel 文件及其从模板 Excel 文件复制的内容。当您单击按钮 1 时,它会打开 VBA 用户窗体,它本身有一个命令按钮,单击时会显示一个消息框。

todo:image_alt_text

示例代码

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
//Create empty target workbook
Workbook target = new Workbook();
//Load the Excel file containing VBA-Macro Designer User Form
Workbook templateFile = new Workbook(sourceDir + "sampleDesignerForm.xlsm");
//Copy all template worksheets to target workboook
foreach (Worksheet ws in templateFile.Worksheets)
{
if (ws.Type == SheetType.Worksheet)
{
Worksheet s = target.Worksheets.Add(ws.Name);
s.Copy(ws);
//Put message in cell A2 of the target worksheet
s.Cells["A2"].PutValue("VBA Macro and User Form copied from template to target.");
}
}//foreach
//-----------------------------------------------
//Copy the VBA-Macro Designer UserForm from Template to Target
foreach (VbaModule vbaItem in templateFile.VbaProject.Modules)
{
if (vbaItem.Name == "ThisWorkbook")
{
//Copy ThisWorkbook module code
target.VbaProject.Modules["ThisWorkbook"].Codes = vbaItem.Codes;
}
else
{
//Copy other modules code and data
System.Diagnostics.Debug.Print(vbaItem.Name);
int vbaMod = 0;
Worksheet sheet = target.Worksheets.GetSheetByCodeName(vbaItem.Name);
if (sheet == null)
{
vbaMod = target.VbaProject.Modules.Add(vbaItem.Type, vbaItem.Name);
}
else
{
vbaMod = target.VbaProject.Modules.Add(sheet);
}
target.VbaProject.Modules[vbaMod].Codes = vbaItem.Codes;
if ((vbaItem.Type == VbaModuleType.Designer))
{
//Get the data of the user form i.e. designer storage
byte[] designerStorage = templateFile.VbaProject.Modules.GetDesignerStorage(vbaItem.Name);
//Add the designer storage to target Vba Project
target.VbaProject.Modules.AddDesignerStorage(vbaItem.Name, designerStorage);
}
}
}//foreach
//Save the target workbook
target.Save(outputDir + "outputDesignerForm.xlsm", SaveFormat.Xlsm);