javavbams-worddocxoffice-2007

Add VBA script to Office Word docs


Is there a library in Java, that allows adding pre-written VBA code into a document ? I have a lot of files, and I need the same code to be inserted in all of the documents.

I have a test with checkboxes, I gave the test to the people who are supposed to answer that, and later the idea of calculating the scores came up to mind and wrote a little of VBA code, now I need to include that on all the test documents once I get them back.

I'm looking for a Java library, but if there is a simpler way to do that in Delphi or VB, that would be great !

Thanks in advance, Regards, Taha


Solution

  • I've injected a macro into an existing docx using docx4j (Java), and via a VSTO Word add-in (C#, OpenXML SDK).

    Here is the docx4j code (not tested recently):

    // Add our macro to the document
    
    // Get vbaProject.bin, and attach it to wordDocumentPart
    
    java.io.InputStream is = ResourceUtils.getResource("docm/vbaProject.bin");                  
    VbaProjectBinaryPart vbaProject = new VbaProjectBinaryPart();
    vbaProject.setBinaryData(is);
    wordDocumentPart.addTargetPart(vbaProject);
    
    // Get /word/vbaData.xml, and attach it to vbaProject
    VbaDataPart vbaData = new VbaDataPart();
    java.io.InputStream is2 = ResourceUtils.getResource("docm/vbaData.xml");                    
    vbaData.setDocument( is2 );
    
    vbaProject.addTargetPart( vbaData);     
    
    // Change the Word document's content type!
    wordDocumentPart.setContentType( new ContentType(
            ContentTypes.WORDPROCESSINGML_DOCUMENT_MACROENABLED ) );
    ContentTypeManager ctm = p.getContentTypeManager();
    PartName partName = wordDocumentPart.getPartName();
    
    ctm.removeContentType( partName  );
    ctm.addOverrideContentType( new java.net.URI("/word/document.xml"), 
            ContentTypes.WORDPROCESSINGML_DOCUMENT_MACROENABLED);