PDA

View Full Version : Solved: Inserting Files and formatting



crowfan
07-31-2007, 07:24 AM
Hello all,

I am trying to consolidate all of the files in a folder into one file. Using the example from the Word VBA help file (under the "InsertFile" entry), I have it working the way that I want. Here it is:

Sub testmacro()

Dim myName As String
Dim myPath As String

Documents.Add Template:="myTemplate.DOT"
Selection.WholeStory
Selection.Collapse Direction:=wdCollapseEnd
myPath = InputBox("Input the file path:")
ChDir myPath
myName = Dir("*.DOC")
While myName <> ""
With Selection
.InsertFile FileName:=myName, ConfirmConversions:=False
.InsertParagraphAfter
.InsertBreak Type:=wdSectionBreakNextPage
.Collapse Direction:=wdCollapseEnd
End With
myName = Dir()
Wend

End Sub
The problem is that the resulting document is a mess, formatting-wise. For example, let's call the created file "File A." I'm creating File A, and then inserting files B, C, and D into it. The problem is that files B, C, and D bring their headers into File A. I want File A's header to remain as it is set in the template (myTemplate.dot in the example above). Also the styles are not the same (files B, C, and D bring their styles into file A), so I'm going to need to convert styles as well.

How do I go about doing something like this? Thanks!

fumei
07-31-2007, 01:23 PM
Don't use InsertFile. It...inserts the file, and files contain the headers.

Use the content. Use a range. Here is a version of your code. Note that the path from the inputbox MUST terminate with a "\". There are other ways to do this.Sub testmacro()

Dim myName As String
Dim myPath As String
Dim rThisDoc As Range
Dim rThatDoc As Range
Dim ThisDoc As Document
Dim ThatDoc As Document

Set ThisDoc = ActiveDocument
Set rThisDoc = ThisDoc.Range
rThisDoc.Collapse Direction:=wdCollapseEnd
myPath = InputBox("Input the file path:")

myName = Dir(myPath & "*.DOC")
Do While myName <> ""
Set ThatDoc = Documents.Open(FileName:=myPath & myName)
Set rThatDoc = ThatDoc.Range
rThatDoc.Copy

With rThisDoc
.Collapse Direction:=wdCollapseEnd
.Paste
.InsertAfter Text:=myPath & myName & " " & vbCrLf
.Collapse Direction:=wdCollapseEnd
.InsertBreak Type:=wdSectionBreakNextPage
.Collapse Direction:=wdCollapseEnd
End With
ThatDoc.Close wdDoNotSaveChanges
myName = Dir()
Loop
End SubThis creates a Range of the working document (I did not bother doing the .Add with your template). It then opens each .doc, makes a range of IT, copies that, pastes that back into the working document, closes the source document.

As a test, I added the instruction to list each file path/name at the end of its content.

Adjust as you see fit. The ranges copied and pasted will take up the styles of the working document.

crowfan
08-08-2007, 12:06 PM
Sorry I never responded to this. I took your advice, and the macro is now running quite smoothly. Thank you.