I need to do some heavy find-replace modifications in a bunch of Word documents and I am trying to speed this up by making this a string operation using the Office Open XML. I can extract the XML encoding from the document, make my modifications but I haven't found a way to inject it back into the document.
Currently my macro looks roughly like this:
Dim sDocXML As String
Dim sXMLReplaced As String
With appWD.ActiveDocument
sDocXML = .Content.WordOpenXML
WriteDown "C:\temp\xml.txt", sDocXML
sXMLReplaced = DoReplacements(sDocXML)
WriteDown "C:\temp\xmlreplaced.txt", sXMLReplaced
????.InsertXML sXMLReplaced
End with
The problem is with the .InsertXML part because I have no idea what to inject where. I tried to do it with .Content level, .Paragraphs.Range level, .Paragraphs(1).Range etc. There seems to be next to no documentation in using the .InsertXML and I guess I am just using it the wrong way. The line always returns an error, either that the object doesn't support the method (where it is not super clear to me which object which method... if it is the final .InsertXML, or if I chained the objects incorrectly together) or most frequently: XML markup cannot be inserted in the specified location.
The DoReplacements function doesn't change any structure of the XML, only the contents of the inner text, using clearly defined delimiters that do not appear outside of it. All I need to do is to is replacing this:
<w:body>
<w:p w:rsidR="000F263E" w:rsidRPr="00B72526" w:rsidRDefault="000F263E" w:rsidP="000F263E">
<w:pPr>
<w:shd w:val="clear" w:color="auto" w:fill="FFFFFF" w:themeFill="background1"/>
<w:spacing w:after="0" w:line="240" w:lineRule="auto"/>
<w:jc w:val="both"/>
<w:rPr>
<w:rFonts w:ascii="Arial" w:eastAsia="Times New Roman" w:hAnsi="Arial" w:cs="Arial"/>
<w:color w:val="000000"/>
<w:sz w:val="18"/>
<w:szCs w:val="18"/>
</w:rPr>
</w:pPr>
<w:r w:rsidRPr="00A84F56">
<w:rPr>
<w:rFonts w:ascii="Arial" w:eastAsia="Times New Roman" w:hAnsi="Arial" w:cs="Arial"/>
<w:color w:val="000000" w:themeColor="text1"/>
<w:sz w:val="18"/>
<w:szCs w:val="18"/>
</w:rPr>
<w:t>{{Date}}</w:t>
</w:r>
</w:p>
</w:body>
to this:
<w:body>
<w:p w:rsidR="000F263E" w:rsidRPr="00B72526" w:rsidRDefault="000F263E" w:rsidP="000F263E">
<w:pPr>
<w:shd w:val="clear" w:color="auto" w:fill="FFFFFF" w:themeFill="background1"/>
<w:spacing w:after="0" w:line="240" w:lineRule="auto"/>
<w:jc w:val="both"/>
<w:rPr>
<w:rFonts w:ascii="Arial" w:eastAsia="Times New Roman" w:hAnsi="Arial" w:cs="Arial"/>
<w:color w:val="000000"/>
<w:sz w:val="18"/>
<w:szCs w:val="18"/>
</w:rPr>
</w:pPr>
<w:r w:rsidRPr="00A84F56">
<w:rPr>
<w:rFonts w:ascii="Arial" w:eastAsia="Times New Roman" w:hAnsi="Arial" w:cs="Arial"/>
<w:color w:val="000000" w:themeColor="text1"/>
<w:sz w:val="18"/>
<w:szCs w:val="18"/>
</w:rPr>
<w:t>01/01/2026</w:t>
</w:r>
</w:p>
</w:body>
And injecting it back to the document (obviously with many more paragraphs and placeholders).

