Thứ Tư, 23 tháng 5, 2012

Gộp nhiều tài liệu Word 2010 thành 1 dùng VB


Merge Multiple Word 2010 Documents

Unarguably Word 2010 is a best word editor around, apart from providing basic editing tools and charting styles, it also provides an option to customize document in any way you want. Concealed by default, Word 2010 provides an option to add different functions, like for example, by inserting few lines of code you can merge Word documents without having to use any dedicated third party app. In this post we will be inserting few lines of code to merge all contents of documents residing in the same folder and show them in a new one.
To begin, first you need to put them in the same folder, make sure that they all belong to same Word version either Doc or Docx. As you can see in the screenshot below, we have opened two documents that will be merged together.
two documents
Now open any Word document and save it as Macro-Enabled document, for this, go to File menu and click Save As.
save as
A dialog will appear, from Save as type, click Word Macro-Enabled Template and click Save.
dotm
We will be using VB editor, so first we need to make Developer tab apparent on Word window. In case you don’t find Developer tab, go to File menu, click Options, and in left pane click Customize Ribbon, from right pane enable Developer check-box. Click OK to to see Developer tab on the ribbon.
developer 1
Now navigate to Developer tab and click Visual Basic.
developer
You will reach VB Editor dialog, from left sidebar double-click ThisDocument to open it’s VB editing window. You will see the code window on the right side. Now put these lines of code in it.
Note: Don’t forget to change the path of the folder where the documents are residing and version of Word documents in these lines of code. To make it easier we have added this precaution in front of the codes as well.

Sub MergeDocs()
Dim rng As Range
Dim MainDoc As Document
Dim strFile As String
Const strFolder = “C:\Users\Usman Javaid\Desktop\Word documents\” ||| (Change the path where your documents are residing)
Set MainDoc = Documents.Add
strFile = Dir$(strFolder & “*.docx”) ||| (Change file extension to .doc incase you are dealing with Word 97-03 version)
Do Until strFile = “”
Set rng = MainDoc.Range
rng.Collapse wdCollapseEnd
rng.InsertFile strFolder & strFile
strFile = Dir$()
Loop
End Sub
vb editor
Now press Ctrl+S to save the newly added macro and close the VB editor. Navigate to Developer tab and click Macros.
macros
From the Macros dialog, select MergeDocs macro and click Run.
macros 1
If you have specified path and version correctly, then all documents would merge and open-up in a new document.
merged
You can also check out our previously reviewed guides on Return to last line edited in Word 2010 and using Mail Merge in Word 2010.
Source: http://www.addictivetips.com/microsoft-office/merge-multiple-word-2010-documents/

Không có nhận xét nào:

Đăng nhận xét

Search 2.0