OpenXML SDK Inject VBA into excel workbook

后端 未结 3 828
梦谈多话
梦谈多话 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:27

    You need to specify "codeName" attribute in the "xl/workbook..xml" object After feeding the VbaProjectPart with macro. Add this code:

    var workbookPr = spreadsheetDocument.WorkbookPart.Workbook.Descendants().FirstOrDefault();
    workbookPr.CodeName = "ThisWorkBook";
    

    After opening the file everything should work now.

    So, to add macro you need to:

    1. Change document type to macro enabled

    2. Add VbaProjectPart and feed it with earlier created macro

    3. Add workbookPr codeName attr in xl/workbook..xml with value "ThisWorkBook"

    4. Save as with .xlsm ext.

提交回复
热议问题