Use Word Macro/VBA to Copy Tables from One Word Document to Another Word Document - vba

I am new to VBA and I would like seek help to create a Word macro to copy certain content tables from Microsoft Office 365 Word Document A to Microsoft Office 365 Word Document B.
Document A has at least 1 content table, but it can have up to, for example, 20 content tables. In order words, the upper bound is dynamic.
1.1 Each content table has two rows and four columns:
1.1.1 the first row has four column cells,
1.1.2 the second row has the first and second column cells merged into one cell, and thus the second row has three columns.
Document B is a blank template. It has some pre-defined text content and then followed by 20 blank content tables. The content table structure in Document B is the same as that in Document A.
The macro needs to do the following:
3.1 Copy the content tables from Document A to Document B in the same sequential order.
3.2 For each content table in Document A, copy as below:
3.2.1 Copy the first row as is to the first row of the corresponding content table in Document B.
3.2.2 Copy the second row as below:
3.2.2.1 Copy the second row’s first column/cell in Document A to the second row’s first column/cell in Document B.
3.2.2.2 Copy the second row’s third column/cell in Document A to the second row’s second column/cell in Document B. That’s all.
I tried to record a macro to do the above but it did not work.
Please kindly advise and help.

Your Document B, which you (probably erroneously) call a template is not blank - it has content. As for the table replication, try:
Sub Demo()
Application.ScreenUpdating = False
Dim DocSrc As Document, DocTgt As Document, t As Long
With Application.FileDialog(FileDialogType:=msoFileDialogFilePicker)
.Title = "Select the source file"
.AllowMultiSelect = False
If .Show = -1 Then
Set DocSrc = Documents.Open(.SelectedItems(1), ReadOnly:=True, AddToRecentFiles:=False)
Else
MsgBox "No source file selected. Exiting", vbExclamation
GoTo ErrExit
End If
End With
With Application.FileDialog(FileDialogType:=msoFileDialogFilePicker)
.Title = "Select the target file"
.AllowMultiSelect = False
If .Show = -1 Then
Set DocTgt = Documents.Open(.SelectedItems(1), ReadOnly:=False, AddToRecentFiles:=False)
Else
MsgBox "No target file selected. Exiting", vbExclamation
DocSrc.Close SaveChanges:=False
GoTo ErrExit
End If
End With
With DocSrc
For t = 1 To .Tables.Count
DocTgt.Tables(t).Range.FormattedText = .Tables(t).Range.FormattedText
DocTgt.Tables(t).Cell(2, 3).Range.Text = vbNullString
DocTgt.Tables(t).Cell(2, 4).Range.Text = vbNullString
Next
.Close False
End With
DocTgt.Activate
ErrExit:
Set DocSrc = Nothing: Set DocTgt = Nothing
Application.ScreenUpdating = True
End Sub

Related

Copy specific column (4) from each table and paste it to the another document in table in column 4 in word document

I am using below code to copy to a column 4 from Source document for all to Column 4 in target document column looping all table of source document table.
As both document has the same table but Source A document has data in column 4 and Source B document didn't have any data in it.
So, trying to copy a data from source A to source B but getting
"Command not available" when I run below code.
I searched for the solution I found that I am using clipboard but instead of clipboard I need to use Range function.
Code:
Sub Demo()
Application.ScreenUpdating = False
Dim DocSrc As Document, DocTgt As Document, t As Long
With Application.FileDialog(FileDialogType:=msoFileDialogFilePicker)
.Title = "Select the source file"
.AllowMultiSelect = False
If .Show = -1 Then
Set DocSrc = Documents.Open(.SelectedItems(1), ReadOnly:=False, AddToRecentFiles:=False)
Else
MsgBox "No source file selected. Exiting", vbExclamation
End If
End With
With Application.FileDialog(FileDialogType:=msoFileDialogFilePicker)
.Title = "Select the target file"
.AllowMultiSelect = False
If .Show = -1 Then
Set DocTgt = Documents.Open(.SelectedItems(1), ReadOnly:=False, AddToRecentFiles:=False)
Else
MsgBox "No target file selected. Exiting", vbExclamation
DocSrc.Close SaveChanges:=False
End If
End With
With DocSrc
For t = 4 To DocSrc.Tables.Count
DocSrc.Tables(t).Columns(4).Select
Selection.Copy
With DocTgt
DocTgt.Tables(t).Columns(4).Select
Selection.Paste
End With
Next
End With
End Sub
As i am not much aware of range function so, need a hint for the same.

Excel to Word VBA Export - Word Documents Not Being Created

I'm running an Excel to Word Export and I cannot create / save new documents based on the template. Each loop will reopen the word template, replaces the <<>> values in the template, and then moves on the next.
(Background - I have a table in Excel consisting 32 rows and 70 columns. I've created a corresponding word template consisting of values to replace from the excel sheet (for instance, <>). On the run, It exports values based on corresponding tags (for instance, <>) in the Excel sheet to the Word Doc). It seems to be working until it gets to WordDoc.SaveAs Filename
The error I get is
Do you want to save your document as the template name? yes / no
it stops there and does not create templates but only changes the template file.
Can anyone suggest a fix to this?
Sub CreateWordDoc()
Dim BenefitRow, BenefitCol, LastRow As Long
Dim TagName, TagValue, Filename As String
Dim WordApp As Word.Application
Dim WordDoc As Word.Document
Dim WordContent As Word.Range
On Error Resume Next
With Sheets("VBA Output")
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True 'Make visible
LastRow = .Range("A9999").End(xlUp).Row 'Determine last row
For BenefitRow = 4 To 6
Set WordDoc = WordApp.Documents.Open(Filename:=" template name.dotm", ReadOnly:=False) 'Open Template saved as .dotm
For BenefitCol = 1 To 79
TagName = .Cells(3, BenefitCol).Value 'Tag Name
TagValue = .Cells(BenefitRow, BenefitCol).Value 'Tag Value
With WordDoc.Content.Find
.Text = TagName
.Replacement.Text = TagValue
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll ',Forward:True, Wrap:wdFindContinue
End With
Next BenefitCol
Filename = ThisWorkbookPath & "\" & .Range("E" & BenefitRow).Value & ".docx"
WordDoc.SaveAs Filename
WordDoc.Close
Next BenefitRow
End With
WordApp.Quit
End Sub
The problem (error message) you're seeing comes from opening a template file then wanting to save it as a "plain vanilla" document. This isn't how Word was designed to be used, which is why Word is basically saying, "Are you sure that's what you want to do?"
A template should not be opened unless the purpose is to change the template, itself. In that case, it would be saved again as a template - no message would be displayed.
When creating new documents from a template use the Documents.Add method:
Set WordDoc = WordApp.Documents.Add(Template:=" template name.dotm")
This automatically creates a copy of the template - there's no danger of overwriting the template. And the message mentioned in the question will not appear when the SaveAs method is executed.

Copy each Word tables from source document to target document loop page by page

I have below code, which copy all tables from source document Tables.docx to target document at the end of document. All below code working without any errors.
In target document Temp.doc, I have table caption either one or two line, then one line blank and one text line starting from word refer appendix as detailed below for better clarity.
Temp.doc
Page 1
TABLE 1. Summary of ........ (table caption)
(one line blank)
Refer Appendix 1 (one text line)
Remaining page blank, where table 1 of page 1 from source doc to be pasted or inserted.
Page 2
TABLE 1 contd. Summary of ........ (table caption)
(one line blank)
Refer Appendix 1 (one text line)
Remaining page blank, where table 2 of page 2 from source doc to be pasted or inserted.
Page 3
TABLE 2. Summary of ........ (table caption)
(one line blank)
Refer Appendix 2 (one text line)
Remaining page blank, where table 3 of page 3 from source doc to be pasted or inserted.
How to copy first page table from source doc to be pasted below line 3 of target doc on page 1. Similarly copy table from page 2 of source doc and paste below line 3 of page 2 of target doc and so on.
I am not having much knowledge of macro. Hence, what I tried to edit below code was not included to reduce confusion to the experts.
Sub ExtractTables()
Dim objTable As Table
Dim SourceDoc As Document
Dim TargetDoc As Document
Dim objRange As Range
Set SourceDoc = WrdApp.Documents.Open(ActiveDocument.Path & "\Tables.docx")
Set TargetDoc = WrdApp.Documents.Open(ActiveDocument.Path & "\Temp.doc")
For Each objTable In SourceDoc.Tables
objTable.Range.Select
Selection.Copy
Set objRange = TargetDoc.Range
objRange.Collapse Direction:=wdCollapseEnd
objRange.PasteSpecial DataType:=wdPasteRTF
objRange.Collapse Direction:=wdCollapseEnd
objRange.Text = vbCr
Next objTable
End Sub
Your description is at best obscure. I have no idea what you might mean by
In target document Temp.doc, I have table caption either one or two
line, then one line blank and one text line starting from word refer
appendix
That said, if you were to insert bookmarks in your Temp.doc to indicate where these copied tables are to go, you might use code like:
Sub CopyTables()
Dim DocSrc As Document, DocTgt As Document, T As Long
Set DocSrc = WrdApp.Documents.Open(ActiveDocument.Path & "\Tables.docx")
Set DocTgt = WrdApp.Documents.Open(ActiveDocument.Path & "\Temp.doc")
With DocSrc
For T = 1 To .Tables.Count
If DocTgt.Bookmarks.Exists("Tbl" & T) Then
DocTgt.Bookmarks("Tbl" & T).Range.FormattedText = .Tables(T).Range.FormattedText
End If
Next
End With
End Sub
The above code assumes the bookmarks in Temp.doc are named Tbl1, Tbl2, etc.
It's also not apparent why you have code like:
Dim WrdApp As Word.Application
Dim bWeStartedWord As Boolean
…
On Error Resume Next
Set WrdApp = GetObject(, "Word.Application")
On Error GoTo 0
If WrdApp Is Nothing Then
Set WrdApp = CreateObject("Word.Application")
bWeStartedWord = True
End If
WrdApp.Visible = True
as there's nothing to indicate any application other than Word is involved.

Copy and paste INCLUDING bookmarks VBA

I have an Excel worksheet from which I am trying to paste Information into a wordfile "Template" (just a word-document in the layout I want), which contains bookmarks. What I would like to do is:
Copy everything in the word document (including bookmarks)
Replace the bookmarks with the data in my sheet
Go to the bottom of the page, insert a page break and paste the copied Text, including bookmarks
Loop through points 2 & 3 for all the rows in my excel file
I have patched together some code, but I'm unable to get the bookmark to paste the text with the bookmarks still intact. Can any of you help me get there?
Sub ReplaceBookmarks
'Select template
PickFolder = "C:\Users\Folder"
Set fdn = Application.FileDialog(msoFileDialogFilePicker)
With fdn
.AllowMultiSelect = False
.Title = "Please select the file containing the Template"
.Filters.Clear
.InitialFileName = PickFolder
If .Show = True Then
Temp = fdn.SelectedItems(1)
End If
End With
'open the word document
Set wdApp = CreateObject("Word.Application")
Set wdDoc = wdApp.Documents.Open(Temp)
'show the word document - put outside of loop for speed later
wdApp.Visible = True
'Copy everything in word document
wdDoc.Application.Selection.Wholestory
wdDoc.Application.Selection.Copy
LastRow2 = 110 ' In real code this is counted on the sheet
For i = 2 To LastRow2
'Data that will replace bookmarks in ws2 (defined somewhere in real code)
Rf1 = ws2.Cells(i, 4).Value
Rf2 = ws2.Cells(i, 2).Value
Rf3 = ws2.Cells(i, 3).Value
'replace the bookmarks with the variables - references sub "Fillbookmark"
FillBookmark wdDoc, Rf1, "Rf1"
FillBookmark wdDoc, Rf2, "Rf2"
FillBookmark wdDoc, Rf3, "Rf3"
' Jump to bottom of document, add page break and paste
With wdDoc
.Application.Selection.EndKey Unit:=wdStory
.Application.Selection.InsertBreak Type:=wdPageBreak
.Application.Selection.PasteAndFormat (wdFormatOriginalFormatting)
End With
Next i
End Sub
Sub FillBookmark(ByRef wdDoc As Object, _
ByVal vValue As Variant, _
ByVal sBmName As String, _
Optional sFormat As String)
Dim wdRng As Object
'store the bookmarks range
Set wdRng = wdDoc.Bookmarks(sBmName).Range
'if the optional format wasn’t supplied
If Len(sFormat) = 0 Then
'replace the bookmark text
wdRng.Text = vValue
Else
'replace the bookmark text with formatted text
wdRng.Text = Format(vValue, sFormat)
End If
End Sub
First try, instead of Copy/Paste, using WordOpenXml. This is much more reliable than copy/paste. Now remember that a Bookmark is a named location, when you copy a section of the document and put it back on another location when the original bookmark is still in place, the new section won't get the copied Bookmark.
I'll provide a little bit of code to show this to you:
Sub Test()
ActiveDocument.Bookmarks.Add Name:="BM1", Range:=ActiveDocument.Paragraphs(1).Range
ActiveDocument.Application.Selection.WholeStory
Dim openxml As String
openxml = ActiveDocument.Application.Selection.wordopenxml
ActiveDocument.Bookmarks(1).Delete
With ActiveDocument
.Application.Selection.EndKey Unit:=wdStory
.Application.Selection.InsertBreak Type:=wdPageBreak
.Application.Selection.InsertXML xml:=openxml
End With
' ActiveDocument.Bookmarks(1).Delete
With ActiveDocument
.Application.Selection.EndKey Unit:=wdStory
.Application.Selection.InsertBreak Type:=wdPageBreak
.Application.Selection.InsertXML xml:=openxml
End With
End Sub
Now open a new document enter some text by entering =Rand() as text in the document and hit enter
Next run the code from the Test macro.
You'll see that because you delete the bookmark using ActiveDocument.Bookmarks(1).Delete from the original part the first inserted text now contains the bookmark, the second does not.
If you uncomment the ' ActiveDocument.Bookmarks(1).Delete line you will see that the bookmark ends up in the second added text part because there is no duplicate bookmark anymore when creating the second section.
So in short, copying a bookmark will not duplicate the bookmark when pasting it, so you need to make sure you either delete the original bookmark or rename the bookmarks to make them unique again. Duplicates is a no go.

Word VBA to Save in specific Directory with Merge Field as File Name and Prompt

Background:
I have created an Excel template to mail merge the fields into a Word document and generate 5 different letters which would go out to ONE customer.
Mission:
To have the Word VBA code run an automatic mail merge and prompt to save (or Autosave) in a specific directory with a file name which is derived from a mail merge field.
ie.
(unique identifier) + Name of First Letter + Date
to be saved in First Letter Folder
(unique identifier) + Name of Second Letter + Date
to be saved in Second Letter Folder
etc..
Issue:
I cannot figure out how to specify the directory or how to insert a mail merge field as a part of the file name.
The following is the code that I have
Sub MailMerge()
With ActiveDocument.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End With
.Execute Pause:=False
End With
With Dialogs(wdDialogFileSummaryInfo)
.Title = "Letter1Draft" & Format(Now(), "mmddyyyy") & ".doc"
.Execute
End With
' Then this!
With Dialogs(wdDialogFileSaveAs)
.Show
End With
End Sub
The following code picks the directory.
It does not allow you to insert a mail merge field as the file name.
Sub AllSectionsToSubDoc()
Dim x As Long
Dim Sections As Long
Dim Doc As Document
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set Doc = ActiveDocument
Sections = Doc.Sections.Count
For x = Sections - 1 To 1 Step -1
Doc.Sections(x).Range.Copy
Documents.Add
ActiveDocument.Range.Paste
ActiveDocument.SaveAs (Doc.Path & "\" & x & ".pdf")
ActiveDocument.Close False
Next x
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub