Want to talk to XMLNodes within your XSD-attached Word document? This week, during one of the ISV coaching sessions, I retrieved a sample available on my system (??? no idea where it came from - was it from Gunther?) demonstrating how you can talk from within VBA to the XML nodes available within the Word document. Here is the code you can copy and paste:
Copy this and put it into a module (change the namespaces):
Option Explicit
Const sNAMESPACE_PREFIX = "ns"
Const sNAMESPACE = "urn:schemas-litware-com.sales.serviceproposal"
Public Sub ResetDocument()
'-------------------------------------------------------------------------------
' Purpose: Clears all of the data out of childless XML nodes
'-------------------------------------------------------------------------------
Dim xNode As XMLNode
On Error GoTo ErrorHandler
For Each xNode In ActiveDocument.XMLNodes
If Not xNode.HasChildNodes Then
xNode.Text = ""
End If
Next xNode
Finally:
Set xNode = Nothing
Exit Sub
ErrorHandler:
MsgBox Err.Description
Resume Finally
End Sub
Public Sub InsertTextInXMLNode(XPath As String, sText As String)
'-------------------------------------------------------------------------------
' Purpose: Inserts text (sText) into a given XML Node determine using an XPath expression (XPath)
'-------------------------------------------------------------------------------
Dim xNode As XMLNode
Dim rng As Range
On Error GoTo ErrorHandler
Set xNode = ActiveDocument.SelectSingleNode(XPath, "xmlns:" & sNAMESPACE_PREFIX & "='" & sNAMESPACE & "'")
Set rng = xNode.Range
rng.Text = sText
Finally:
Set xNode = Nothing
Set rng = Nothing
Exit Sub
ErrorHandler:
MsgBox Err.Description
Resume Finally
End Sub
And here is the code to call this function:
InsertTextInXMLNode "//ns:Client/ns:Company", ddnClients.Value
InsertTextInXMLNode "//ns:Client/ns:ClientID", txtClientID.Text
InsertTextInXMLNode "//ns:Client/ns:Contact", txtContact.Text
InsertTextInXMLNode "//ns:Client/ns:Address", txtAddress.Text
InsertTextInXMLNode "//ns:Client/ns:City", txtCity.Text
InsertTextInXMLNode "//ns:Client/ns:State", txtState.Text
InsertTextInXMLNode "//ns:Client/ns:ZIP", txtZIP.Text
Anyone who wants the full sample, just mail me!