PDA

View Full Version : [SOLVED:] VBA split word document



wannabeguru
01-12-2016, 02:44 PM
Hi gurus,

I am looking for VBA code that will split an existing word document in to two word documents.

I want pages 1 - 4 to be in one word document and pages 5 - last page in another word document (the amount of pages will vary). I would also like all of the existing formatting to be present in both word documents.

Please help! I have been trying to figure it out myself all day and am about to lose my mind!

Thank you very much to anyone who responds.

gmayor
01-13-2016, 12:09 AM
This is fairly simple. Create two copies of the document, by using the saved document as a template. Locate the end of page 4 in each and delete the preceding text in one and the following text in the other.
Option Explicit

Sub SplitDoc()
Dim oSource As Document
Dim oDoc2 As Document
Dim oDoc1 As Document
Dim oRng As Range
'Assign a variable name to the active document
Set oSource = ActiveDocument
'Save the document
oSource.Save
'Create two (un-named) copies of the original document
Set oDoc2 = Documents.Add(oSource.FullName)
Set oDoc1 = Documents.Add(oSource.FullName)
'Process the first copy to delete the pages after page 4
oDoc1.Activate
Selection.GoTo What:=wdGoToPage, Which:=wdGoToFirst, Count:=4, Name:=""
Set oRng = oDoc1.Range
oRng.End = Selection.Bookmarks("\page").Range.End
oRng.Delete
'Process the second copy to delete the pages to page 5
oDoc2.Activate
Selection.GoTo What:=wdGoToPage, Which:=wdGoToFirst, Count:=4, Name:=""
Set oRng = oDoc2.Range
oRng.Start = Selection.Bookmarks("\page").Range.End
oRng.Delete
lbl_Exit:
Set oSource = Nothing
Set oDoc1 = Nothing
Set oDoc2 = Nothing
Set oRng = Nothing
Exit Sub
End Sub

wannabeguru
01-13-2016, 11:44 AM
Thank you gmayor! Much appreciated. This is working when I run the sub by itself, but won't work when I include it at the end of another sub.

Is there a way to create named copies of the original, rather than un-named?

Thanks again

gmayor
01-13-2016, 10:21 PM
To name the documents you will have to save them. Save the two documents oDoc1 and oDoc2. before lbl_Exit: e.g.

oDoc1.SaveAs "C:\Path\Filename.docx"
oDoc2.SaveAs "C:\Path\AnotherFilename.docx" Change the paths and names as appropriate. The path(s) must however exist.
I cannot comment on 'another sub' without knowing anything about that sub.