Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Please help with a macro in Microsoft Word 2007

Status
Not open for further replies.

AKMMS

Technical User
Jun 23, 2010
1
US
I need help with the macro at the bottom of this post.

This macro is supposed to take a large Word document and save each page as a new, separate file.

The master file I am trying to separate is 213 pages. When I run the macro, it generates 213 new files, but the problem is that each new file it generates is the first page of the master file. In other words, all 213 new files are exactly the same.

Does anyone know why this would happen? What in the macro would cause it to create 213 copies of page 1 instead of 1 copy of each of the 213 pages in the master file?

Thanks in advance!

---


Sub SavePagesAsDoc()

Dim orig As Document
Dim page As Document
Dim numPages As Integer
Dim idx As Integer
Dim fn As String


' Keep a reference to the current document.
Set orig = ActiveDocument

' Calculate the number of pages
numPages = ActiveDocument.Range.Information(wdActiveEndPageNumber)

For idx = 1 To numPages
' Make sure the document is active
orig.Activate

' Go to the page with index idx
Selection.GoTo What:=wdGoToPage, Name:=idx

' Select the current page
Selection.GoTo What:=wdGoToBookmark, Name:="\page"

' Copy the selection
Selection.Copy

' Create a new document
Set page = Documents.Add

' Activate it
page.Activate

' Paste the selection
Selection.PasteAndFormat wdFormatOriginalFormatting

' Generate the file name
fn = "Page" + CStr(idx) + ".doc"

' Save the document as Word 97-2003
page.SaveAs FileName:=fn, FileFormat:=wdFormatDocument, AddToRecentFiles:=False

' Close the document
page.Close

Next

End Sub
 
I created a word document with 6 pages each with a number on it and it worked fine. saved 6 new documents with each page.

Impossible is Nothing
 
It works for me as well. The code could be a little simpler though.
Code:
Sub SavePagesAsDoc()
Dim orig As Document
Dim page As Document
Dim idx As Long
Dim r As Range

' Keep a reference to the current document.
Set orig = ActiveDocument

For idx = 1 To ActiveDocument.Range.Information(wdActiveEndPageNumber)
   ' Go to the page with index idx
   Selection.GoTo What:=wdGoToPage, Name:=idx
   Set r = orig.Bookmarks("\page").Range
   Set page = Documents.Add
   page.Range = r
   ' Save the document as Word 97-2003
   page.SaveAs FileName:="Page" + CStr(idx) + ".doc", _
      FileFormat:=wdFormatDocument, _
      AddToRecentFiles:=False
   ' Close the document
   page.Close
Next
End Sub

Gerry
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top