Copy vba code to another xlsm file using Open XML from a template xlsm file

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 05:06:46

问题


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

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.


回答1:


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.



来源:https://stackoverflow.com/questions/12722314/copy-vba-code-to-another-xlsm-file-using-open-xml-from-a-template-xlsm-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!