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
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:
ReplyDeletePrivate 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