Monday, January 30, 2012

How to Export Parts of Document using Word VBA

Copy Content with Formatting to New Document using Word VBA

Not all the tens and hundreds of pages in a Word document interests you or matters to you. There are some documents, which we use for reference. All we need is a paragraph/section from the document. If it is a book we used to take a photo-copy of the same and keep it in a folder. How to do the same in a Word document - and in an automated way with all the formatting intact?

 ExportFragment method in Word VBA provides the solution. It creates a new document from the existing one for the Range of your choice.

Here is an example where it exports eleventh paragraph of the document to a new one.

Sub PartofText()

Dim oWDRange As Word.Range

Set oWDRange = ActiveDocument.Paragraphs(11).Range
oWDRange.ExportFragment "D:\Documents and Settings\Admin\My Documents\Reference_11.docx", wdFormatDocumentDefault

End Sub

See also

1 comment:

  1. Thanks for this snippet. It works well when inserting the full path and filename in the code. I tried to customize it a bit to let users pick the location of their choice. It exports the fragment in the new location but there is an error when trying to open the exported file. It says "unsupported file type" or "file cannot be opened because there are problems with the content". Copying code below:

    Private Sub CommandButton1_Click()
    Dim oWDRange As Word.Range

    Dim strFileName As String
    Dim StrPath As String
    'provide default filename
    StrPath = "c:\temp\test.docx"
    With Dialogs(wdDialogFileSaveAs)
    .Name = StrPath
    If .Display <> 0 Then
    strFileName = .Name
    Else
    End
    End If
    End With

    Set oWDRange = ActiveDocument.Sections(2).Range
    oWDRange.ExportFragment strFileName, wdFormatDocumentDefault

    End Sub

    Any help you can provide will be greatly appreciated.

    Jess

    ReplyDelete

StumbleUpon
Share on Facebook
Related Posts Plugin for WordPress, Blogger...

Visual Basic for Applications (VBA) Forum (recent threads)

CodeKeep VBA Feed

Visual Studio Tools for Office Forum (recent threads)

Download Windows Live Toolbar and personalize your Web experience! Add custom buttons to get the information you care about most.

Office Business Applications (OBA) Team Blog

MSDN Code Gallery Published Resources For Tag VSTO

microsoft.public.vsnet.vstools.office Google Group