In C#/.NET I am able to open a DOCX file as 开发者_开发技巧a ZipPackage
, then manipulate its XML parts separately by getting them as PackagePart
s and reading from / writing to their Stream
s 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 ZipPackage
s, 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 PackagePart
s 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 Part
s and change things with XSLT or other XML manipulation technologies - but you wouldn't be able to do this on the ActiveDocument
because 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.
精彩评论