テンプレートから対象のブックへVBAマクロのUserForm DesignerStorageをコピー
可能な使用シナリオ
Aspose.Cells for Python via .NETは、一つのExcelファイルから別のExcelファイルへVBAプロジェクトをコピーすることを可能にします。VBAプロジェクトは、ドキュメント、手続き、デザイナーなど様々なタイプのモジュールで構成されています。すべてのモジュールは簡単なコードでコピー可能ですが、デザイナーモジュールにはDesigner Storageと呼ばれる追加データがあり、これにアクセスまたはコピーが必要です。以下の二つのメソッドは、Designer Storageを扱います。
テンプレートからターゲットワークブックへのVBAマクロUserForm DesignerStorageのコピー
次のサンプルコードをご覧ください。それは、テンプレートExcelファイルからVBAプロジェクトを空のワークブックにコピーし、出力Excelファイルとして保存します。テンプレートExcelファイル内のVBAプロジェクトを開くと、以下に示すようにUser Formが表示されます。User FormにはDesigner Storageが含まれているため、VbaModuleCollection.get_designer_storage()およびVbaModuleCollection.add_designer_storage()メソッドを使用してコピーされます。
以下のスクリーンショットは、テンプレートExcelファイルからコピーされた出力Excelファイルとその内容を示しています。ボタン1をクリックすると、VBAユーザーフォームが開きます。VBAユーザーフォームには、クリックするとメッセージボックスが表示されるコマンドボタンがあります。
サンプルコード
from aspose.cells import SaveFormat, SheetType, Workbook | |
from aspose.cells.vba import VbaModuleType | |
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
# Create empty target workbook | |
target = Workbook() | |
# Load the Excel file containing VBA-Macro Designer User Form | |
templateFile = Workbook(sourceDir + "sampleDesignerForm.xlsm") | |
# Copy all template worksheets to target workboook | |
for ws in templateFile.worksheets: | |
if ws.type == SheetType.WORKSHEET: | |
s = target.worksheets.add(ws.name) | |
s.copy(ws) | |
# Put message in cell A2 of the target worksheet | |
s.cells.get("A2").put_value("VBA Macro and User Form copied from template to target.") | |
# ----------------------------------------------- | |
# Copy the VBA-Macro Designer UserForm from Template to Target | |
for vbaItem in templateFile.vba_project.modules: | |
if vbaItem.name == "ThisWorkbook": | |
# Copy ThisWorkbook module code | |
target.vba_project.modules.get("ThisWorkbook").codes = vbaItem.codes | |
else: | |
# Copy other modules code and data | |
print(vbaItem.name) | |
vbaMod = 0 | |
sheet = target.worksheets.get_sheet_by_code_name(vbaItem.name) | |
if sheet == None: | |
vbaMod = target.vba_project.modules.add(vbaItem.type, vbaItem.name) | |
else: | |
vbaMod = target.vba_project.modules.add(sheet) | |
target.vba_project.modules[vbaMod].codes = vbaItem.codes | |
if vbaItem.type == VbaModuleType.DESIGNER: | |
# Get the data of the user form i.e. designer storage | |
designerStorage = templateFile.vba_project.modules.get_designer_storage(vbaItem.name) | |
# Add the designer storage to target Vba Project | |
target.vba_project.modules.add_designer_storage(vbaItem.name, designerStorage) | |
# Save the target workbook | |
target.save(outputDir + "outputDesignerForm.xlsm", SaveFormat.XLSM) |