OpenXML SDK Inject VBA into excel workbook

后端 未结 3 826
梦谈多话
梦谈多话 2021-02-06 06:52

I can successfully inject a piece of VBA code into a generated excel workbook, but what I am trying to do is use the Workbook_Open() event so the VBA code executes when the file

3条回答
  •  别那么骄傲
    2021-02-06 07:18

    I found that the other answers still resulted in the duplicate "Worksheet" object. I used a similar solution to what @ZlotaMoneta said, but with a different syntax found here:

    List newParts = new List();
    using (var originalDocument = SpreadsheetDocument.Open("file1.xlsm"), false))
    {
        newParts = originalDocument.WorkbookPart.GetPartsOfType().ToList();
    
        using (var document = SpreadsheetDocument.Open("file2.xlsm", true))
        {
            document.WorkbookPart.DeleteParts(document.WorkbookPart.GetPartsOfType());
    
            foreach (var part in newParts)
            {
                VbaProjectPart vbaProjectPart = document.WorkbookPart.AddNewPart();
                using (Stream data = part.GetStream())
                {
                    vbaProjectPart.FeedData(data);
                }                    
            }
    
            //Note this prevents the duplicate worksheet issue
            spreadsheetDocument.WorkbookPart.Workbook.WorkbookProperties.CodeName = "ThisWorkbook";
        }
    }
    

提交回复
热议问题