1

I use this code to add VbaPart of the template xlsm file into another. When I open the vb section duplicate entries get added for each sheet as well as the "ThisWorkBook".

Below is the screen shot of how it looks in the developer tab enter image description here

And below is the code that I use:

using (SpreadsheetDocument myDoc = SpreadsheetDocument.Open(convertDocumentFile, true))
{
    VbaProjectPart extendedPart = FindPart(myDoc);

    if (extendedPart != null)
      myDoc.DeletePart(extendedPart);
    if (vbaPart != null)
      myDoc.WorkbookPart.AddPart<VbaProjectPart>(vbaPart);
}

private static VbaProjectPart FindPart(SpreadsheetDocument mainPart)
{
    if (mainPart != null)
    {
        foreach (IdPartPair partPair in mainPart.WorkbookPart.Parts)
        {
            if (partPair.OpenXmlPart.RelationshipType == _wnsRelationShip.NamespaceName)
            {
               return partPair.OpenXmlPart as VbaProjectPart;
            }
        }
    }
    return null;
}

Where the variable "convertDocumentFile" is the file where the vbaProject part needs to be added and the "vbaPart" is the vbaProjectPart from the template.

Community
  • 1
  • 1
user581157
  • 1,327
  • 4
  • 26
  • 64

1 Answers1

2

The reason my code did not execute was that the "CodeName" attribute was missing when I converted to xlsm format hence I need to add the following code:

myDoc.WorkbookPart.Workbook.WorkbookProperties.CodeName = "ThisWorkbook";

After pointing to the correct workbook, the vb code executed correctly.

David Rogers
  • 2,601
  • 4
  • 39
  • 84
user581157
  • 1,327
  • 4
  • 26
  • 64