将VBA宏用户表单DesignerStorage从模板复制到目标工作簿

可能的使用场景

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

将VBA宏用户表单DesignerStorage从模板复制到目标工作簿

请参见以下示例代码。它将从模板Excel文件中复制VBA项目到一个空工作簿,并将其保存为输出Excel文件。如果您打开模板Excel文件中的VBA项目,您将看到如下所示的用户表单。用户表单包含设计师存储,因此将使用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);