Insert a Document from outside in Word using VBA code

Insert a Document from outside in Word using VBA code

InsertFile

Method brings entire or part of the specified document in the current Document. Microsoft Word offers Selection object, exposes InsertFile method by which you can bring external file directly inside current working document and render the contents. It is something like you open an external document in a separate window and selects all then Copy and then paste it inside your current working document.

Syntax

InsertFile( FileName , Range , ConfirmConversions , Link , Attachment )

Parameters

  1. FileName: File path which you would like to insert.
  2. Range: depends on the file type, if file type is Word (which needs to be inserted) then it would be referred as Bookmark, If type is Excel the it would be considered as Name Range.
  3. ConfirmConversions: its boolean argument, if sets to True the Word would prompt conversion.
  4. Link: a boolean argument, if set to True then file will be inserted as INCLUDETEXT field.
  5. Attachment: boolean parameter, if sets to True then file will be inserted as attachment like email attachment.

Link Code example

Public Sub InsertFile()
	Selection.Collapse Direction:=wdCollapseEnd 
	Selection.InsertFile FileName:="C:\MyDocument.DOCX", Link:=True
End Sub

This example creates a new document and then inserts the contents of each text file in the C:\Apps folder into the new document.

Code example

Public Sub InsertFileMethod()
	Documents.Add 
	ChDir "C:\Apps" 
	myName = Dir("*.TXT") 
	While myName <> "" 
		 With Selection 
			 .InsertFile FileName:=myName, ConfirmConversions:=False 
			 .InsertParagraphAfter 
			 .InsertBreak Type:=wdSectionBreakNextPage 
			 .Collapse Direction:=wdCollapseEnd 
		 End With 
	 myName = Dir() 
	Wend
End Sub

Next>>Range Object Word Document VBA

Leave a Reply

Your email address will not be published. Required fields are marked *