VBA Macro Help: Copy/Filtering Selection.Range.XML to Clipboard

fcqmax
fcqmax used Ask the Experts™
on
Currenly I'm using this code to copy WordML to clipboard in Word 2003:

Sub copyXMLToClipboard()
Dim DataObj As New MSForms.DataObject
    Dim S As String
    S = Selection.Range.XML
    DataObj.SetText S
    DataObj.PutInClipboard
End Sub

But I found out that it is copying too much info into the clipboard, I would like to limit the copy selection to only the content within the <wx:sect></wx:sect> tags and nothing else.

Here's an example, if Selection.Range.XML has the following content:

<w:wordDocument>
  <o:DocumentProperties>
    ...XML content here...
  </o:DocumentProperties>
  <w:fonts>
    ...XML content here...
  </w:fonts>
  <w:body>
    <wx:sect>
      <w:p>
        ...My XML content here...
      </w:p>
      <w:p>
         ...My XML content here...
      </w:p>
    </wx:sect>
  </w:body>
</w:wordDocument>


What I'd like is a macro which copies Selection.Range.XML into a variable, strips out everything I don't want. And the resulting XML in the clipboard should be:

      <w:p>
        ...My XML content here...
      </w:p>
      <w:p>
         ...My XML content here...
      </w:p>
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Software Architect in .Net
Commented:
Limit the selection by yourself:

Sub copyXMLToClipboard()
Dim DataObj As New MSForms.DataObject
    Dim S As String
    S = Selection.Range.XML

    'Define start & end tags
    Const StartTag As String = "<wx:sect>"
    Const EndTag As String = "</wx:sect>"

    'Get the position into the text in which are the start & end tags
    Dim startPos As Integer
    startPos = InStr(S, StartTag)
    Dim endPos As Integer
    endPos = InStr(S, EndTag) + Len(EndTag)

    'Re-build the string extracting only desired part
    S = Mid(S, startPos, endPos - startPos)

    DataObj.SetText S
    DataObj.PutInClipboard
End Sub

Hope that helps.

Author

Commented:
Thanks! But I get this error upon execution:

-- Error Dialog --

Run-time error '6';

Overflow

------------------


startPos = InStr(S, StartTag) <-- This line is highlighted

Author

Commented:
Thanks, I had to change integer to long for it to work in my situation

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial