开发者

Manipulation of DOCX in VBA?

In C#/.NET I am able to open a DOCX file as 开发者_开发技巧a ZipPackage, then manipulate its XML parts separately by getting them as PackageParts and reading from / writing to their Streams using .GetStream().

As far as I'm aware, VBA is a million miles away from having this functionality (especially given that I've not found anything about it after a lot of web searching), but I just thought I'd check: can any VBA aficionados confirm or deny whether VBA has some kind of built-in functionality for manipulating DOCX ZipPackages, or would you pretty much have to write your own VBA DOCX parser from scratch?


Mostly the answer is no, but there is a glimmmer of yes.

Regarding your specific question of managing PackageParts from their streams. You could probably do this with some kind of "unzip" utility and then knowing the OPC structure, navigate to whereever you want in the Parts and change things with XSLT or other XML manipulation technologies - but you wouldn't be able to do this on the ActiveDocumentbecause its stream is already in use by nature of it being open. You could use VBA to create a copy of it and manipulate that one in a really cumbersome manner and when your manipulation is done, have VBA close and delete the current ActiveDocument and open your manipulated one as the new ActiveDocument.

On the other hand, there is a way to manipulate WordprocessingML for the current ActiveDocument from VBA, but it would be incredibly difficult to do. Have an open document, select something and then to the VBE. Then run this:

Sub InjectXML()
    Dim wd As Document: Set wd = ActiveDocument
    Debug.Print wd.Range.WordOpenXML
End Sub

You'll see all the WordprocessingML spit out in the immediate window. This is actually "Flat OPC WordprocessingML" as it is all maintained in a single string of XML. By using ActiveDocument.Range.InsertXML, you could technically insert Flat OPC-type of WordprocessingML back into the document at the selected location. Here's an example of someone using C# to do this via interop and Linq-to-XML. To do this in VBA would be incredibly hard.

So again, the answer is mostly "no", but a little bit of "yes".


You do not state your ultimate aim, but I guess one possibility is to use Microsoft.office.interop.word to manipulate the word document.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜