I have two partial working bits of code to put together.
I have a worksheet labeled 'word' that I want to export and save automatically under a variable.
Sub CreateNewWordDoc()
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Dim i As Integer
docname = Worksheets("input").Range("b10").Value
Data1 = Worksheets("word").Range("a1:d103").Value
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Open("C:\Results\ResultsTemplate.doc")
'******THIS IS TO EDIT THE WORD DOCUMENT******
With Worksheets("word")
CopyRangeToWord wdDoc, .Range("A1:d104")
'******THIS IS THE END TO EDIT THE WORD DOCUMENT*****
If Dir("C:\Results\" & docname & ".doc") <> "" Then
Kill "C:\Results\" & docname & ".doc"
End If
.SaveAs ("C:\Results\" & docname & ".doc")
.Close ' close the document
End With
wrdApp.Quit ' close the Word application
Set wrdDoc = Nothing
Set wrdApp = Nothing
End Sub
I like this first one the best. It will open my template that has all the official stuff that these generated reports will require (company info etc) and will automatically save and close with the correct file name. However, I cannot find a way to get it to copy all the information from the worksheet 'word' into the text body of the document. It is saving a blank document.
While troubleshooting, I came across this code:
Private Sub CopyRangeToWord(ByRef wdDoc As Word.Document, rng_to_copy As Range, Optional page_break As Boolean = True)
' Will copy the range given into the word document given.
Application.StatusBar = "Copying data from " & rng_to_copy.Parent.Name & "..."
rng_to_copy.Copy
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.InsertParagraphAfter
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.Paste
Application.CutCopyMode = False
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.InsertParagraphAfter
' insert page break after all worksheets except the last one
If page_break Then
With wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range
.InsertParagraphBefore
.Collapse Direction:=wdCollapseEnd
.InsertBreak Type:=wdPageBreak
End With
End If
End Sub
Sub CopyWorksheetsToWord()
Dim wdApp As Word.Application, wdDoc As Word.Document, ws As Worksheet
Application.ScreenUpdating = False
Application.StatusBar = "Creating new document..."
Set wdApp = New Word.Application
Set wdDoc = wdApp.Documents.Add
docname = Worksheets("input").Range("b10").Value
With Worksheets("word")
CopyRangeToWord wdDoc, .Range("A1:d104")
End With
Set ws = Nothing
Application.StatusBar = "Cleaning up..."
'apply normal view
With wdApp.ActiveWindow
If .View.SplitSpecial = wdPaneNone Then
.ActivePane.View.Type = wdNormalView
Else
.View.Type = wdNormalView
End If
End With
Set wdDoc = Nothing
wdApp.Visible = True
Set wdApp = Nothing
Application.StatusBar = False
End Sub
which does the exact opposite of the first code: it will open up a new document (not the template), will copy all the data perfectly but will not save or close with correct filenames.
I am guessing that it will be easier to update code section one to copy the worksheet contents, and is what I would prefer.
Private Sub CopyRangeToWord(ByRef wdDoc As Word.Document, rng_to_copy As Range, Optional page_break As Boolean = True)
' Will copy the range given into the word document given.
Application.StatusBar = "Copying data from " & rng_to_copy.Parent.Name & "..."
rng_to_copy.Copy
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.InsertParagraphAfter
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.Paste
Application.CutCopyMode = False
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.InsertParagraphAfter
' insert page break after all worksheets except the last one
If page_break Then
With wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range
.InsertParagraphBefore
.Collapse Direction:=wdCollapseEnd
.InsertBreak Type:=wdPageBreak
End With
End If
End Sub
Sub CopyWorksheetsToWord()
Dim wdApp As Word.Application, wdDoc As Word.Document, ws As Worksheet
Application.ScreenUpdating = False
Application.StatusBar = "Creating new document..."
Set wdApp = New Word.Application
Set wdDoc = wdApp.Documents.Add
docname = Worksheets("input").Range("b10").Value
With Worksheets("word")
CopyRangeToWord wdDoc, .Range("A1:d104")
With wdDoc
.SaveAs ("C:\Results\" & docname & ".doc")
.Close
End With
End With
End Sub
this works: but does not open from my template. nonetheless - it will create a document from one worksheet and automatically save it to the directory with the filename referenced in a defined cell.
Related
I have a few Word files with the Tables containing Data which I want to export to excel. I've found a script that did it manually. I modified it in the hopes of having it automatically do the same for all files. Each table it finds gets put into a new sheet and then I want it to save with the same File name as the word document. After running the code I get a Compile Error : Type Mismatch which points towards folder = Dir("C:\Users\user\Desktop\folder"). Here's the code :
Option Explicit
Sub AA()
Dim oWord As Word.Application
Dim WordNotOpen As Boolean
Dim file As Word.Document
Dim oTbl As Word.Table
Dim FilePath As String
Dim wbk As Workbook
Dim wsh As Worksheet
Dim folder As Object
' Prompt for document
Application.ScreenUpdating = False
' Create new workbook
Set wbk = Workbooks.Add(Template:=xlWBATWorksheet)
' Get or start Word
Set oWord = GetObject(Class:="Word.Application")
If Err Then
Set oWord = New Word.Application
WordNotOpen = True
End If
'On Error GoTo Err_Handler
' Open document
Set folder = Dir("C:\Users\user\Desktop\folder")
For Each file In folder
If file.GetExtensionName(file.Path) = "docx" Then
FilePath = "C:\Users\user\Desktop\folder\" & file & ".docx"
Debug.Print FilePath
Set file = oWord.Documents.Open(Filename:=FilePath)
' Loop through the tables
For Each oTbl In file.Tables
' Create new sheet
Set wsh = wbk.Worksheets.Add(After:=wbk.Worksheets(wbk.Worksheets.Count))
' Copy/paste the table
oTbl.Range.Copy
wsh.Paste
Next oTbl
' Delete the first sheet
Application.DisplayAlerts = False
wbk.Worksheets(1).Delete
Application.DisplayAlerts = True
wsh.SaveAs Filename:=""
End If
Next
'Exit_Handler:
'On Error Resume Next
' oDoc.Close SaveChanges:=False
'If WordNotOpen Then
' oWord.Quit
' End If
' 'Release object references
' Set oTbl = Nothing
'Set oDoc = Nothing
' Set oWord = Nothing
'Application.ScreenUpdating = True
' Exit Sub
'Err_Handler:
' MsgBox "Word caused a problem. " & Err.Description, vbCritical, "Error: " & Err.Number
' Resume Exit_Handler
End Sub
I am trying to copy all the text, with formatting intact, from each of multiple Word Documents, and paste the text of each into a new cell in a single Excel Spreadsheet, placing the name of the Word Doc in an adjacent cell.
So the file name of "Document 1" goes in cell A1, and the entire contents of "Document 1" goes in cell A2.
We have several hundred Documents that need to be imported onto pages on our new corporate Intranet, and the migration tool provided only works off data in an Excel workbook.
I've checked out a number of threads, videos, and searches and tried to cobble together a couple of different attempts but neither is working. The first, if it did work, may not handle the File Name copy and it seems to run into issues with selecting the destination cell for the copy.
The second seems to be exactly what I want, but I can;t get the Paste into Excel bit working.
The first runs into an issue when it hits the "Range("LastRow").PasteSpecial xlPasteValues" line, saying the range is invalid (I have defined "LastRow" in the Excel Workbook but it doesn't help) :
Sub Copy_Data_From_Multiple_WordFiles()
Dim FolderName As String
Dim FileName As String
Dim NewWordFile As New Word.Application
Dim NewDoc As New Word.Document
Application.DisplayAlerts = False
'Application.ScreenUpdating = False
FolderName = "C:\Test\"
FileName = Dir(FolderName)
'Loop start
Do While FileName ⋖⋗ ""
Set NewDoc = NewWordFile.documents.Open(FolderName & FileName)
NewDoc.Range(0, NewDoc.Range.End).Copy
Range("LastRow").PasteSpecial xlPasteValues
NewDoc.Close SaveChanges:=wdDoNotSaveChanges
NewWordFile.Quit
FileName = Dir()
Loop
End Sub
NB: LastRow is defined in Excel Name Manager as:=OFFSET(CopyDataFromWord!$A$1,COUNTA(CopyDataFromWord!$A:$A),0,1,1)
I have tried a second set of code I got from a post on here, which should be closer to what I'm seeking, but again, won't quite get there. This one fails with a "Run-Time error '424': Object Required" at the line where it should paste into Excel. It doesn't seem to be recognising the Object "objDoc"?
Sub Excel_Word()
Dim WordApp As Object 'New Word.Application
Dim objDoc As Object ' New Word.Document
Dim Range As Object 'Word.Range
Dim WordDoc As String
Dim sPath As String
Dim i As Long
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True
sPath = "C:\Users\jdodd\Documents\Cleaned\"
WordDoc = Dir(sPath & "*.docx")
Do While WordDoc <> ""
Set objDoc = WordApp.Documents.Open(sPath & WordDoc)
objDoc.Range.Copy
i = i + 1
ImportPolicyfromWord.Cells(i, 1).Value = objDoc
ImportPolicyfromWord.Cells(i, 2).Value = objDoc.Range.PasteSpecial
WordDoc = Dir()
Loop
WordApp.Quit
'elimina variabili
'Set WordApp = Nothing
'Set objDoc = Nothing
End Sub
Appreciate any advice or help
Try:
Sub GetDocData()
'Note: this code requires a reference to the Word object model.
'See under the VBE's Tools|References.
Application.ScreenUpdating = False
Dim strFolder As String: strFolder = GetFolder: If strFolder = "" Then GoTo ErrExit
Dim wdApp As New Word.Application, wdDoc As Word.Document
Dim strFile As String, WkSht As Worksheet, r As Long
Set WkSht = ActiveSheet
'Disable any auto macros in the documents being processed
wdApp.WordBasic.DisableAutoMacros
'Disable any alerts in the documents being processed
wdApp.DisplayAlerts = wdAlertsNone
strFile = Dir(strFolder & "\*.doc", vbNormal)
While strFile <> ""
Set wdDoc = wdApp.Documents.Open(Filename:=strFolder & "\" & strFile, AddToRecentFiles:=False, Visible:=False)
With wdDoc
.ConvertNumbersToText (wdNumberAllNumbers)
With .Range.Find
.ClearFormatting
.Replacement.ClearFormatting
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchWildcards = True
.Text = "[^12^13^l]{1,}"
.Replacement.Text = "¶"
.Execute Replace:=wdReplaceAll
.Text = "[^t]"
.Replacement.Text = " "
.Execute Replace:=wdReplaceAll
End With
r = WkSht.UsedRange.Cells.SpecialCells(xlCellTypeLastCell).Row
If r > 1 Then r = r + 2
WkSht.Range("A" & r).Value = .Name
.Range.Copy
r = r + 1
WkSht.Paste Destination:=WkSht.Range("A" & r)
.Close SaveChanges:=False
End With
strFile = Dir()
Wend
ErrExit:
wdApp.Quit
WkSht.UsedRange.Replace What:="¶", Replacement:=Chr(10), LookAt:=xlPart, SearchOrder:=xlByRows
Set wdDoc = Nothing: Set wdApp = Nothing: Set WkSht = Nothing
Application.ScreenUpdating = True
End Sub
Function GetFolder() As String
Dim oFolder As Object
GetFolder = ""
Set oFolder = CreateObject("Shell.Application").BrowseForFolder(0, "Choose a folder", 0)
If (Not oFolder Is Nothing) Then GetFolder = oFolder.Items.Item.Path
Set oFolder = Nothing
End Function
Simply select the folder to process. As coded, the macro places the document name above the contents, which are all pasted into one cell. If you want the document name on the same row, but beside the contents, change:
r = r + 1
WkSht.Paste Destination:=WkSht.Range("A" & r)
to:
WkSht.Paste Destination:=WkSht.Range("B" & r)
I'm trying to create a code that reads a dynamic Excel table into an existing Word document and changes some variables in the document (for example %Username%)
The code below gives me an "Locked for editing" error by myself, but that isn't the case.
Can someone see what I have to change in the code?
The code is:
Sub Export_Table_Word()
'Word objects.
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim wdbmRange As Word.Range
'Excel objects.
Dim wbBook As Workbook
Dim wsSheet As Worksheet
Dim rnReport As Range
'Path of Word Template
Dim stPathTemplate As String
Dim stPathSave As String
'Dynamic Replace variables
Dim UserName As String
Dim StrFind
Dim StrRepl As String
'Loop variable
Dim i As Long
Dim msWord As Object
Set msWord = CreateObject("Word.Application")
'Define replacement variables
UserName = Application.UserName
sFirst = Split(UserName, " ")(0) 'Firstname 'sFirst = Split(UserName, ",")(1) 'Firstname
sLast = Split(UserName, " ")(1) 'Lastname
sUserName = Left(sFirst, 1) & sLast 'First letter of firstname and lastname
sFullName = sFirst & " " & sLast 'Full name
StrFind = "%User_Name%,%Full_name%, %Date%" 'Strings to be replaced in the word document
StrRepl = sUserName & "*" & sFullName & "*" & " " & Date 'Replaced by
'Initialize Path word template
stPathTemplate = "C:\Users\xxx\Desktop\VBA_TEST\VBA_Automation.docx"
stPathSave = "C:\Users\xxx\Desktop\VBA_TEST\Finished.docx"
'Initialize the Excel objects.
Set wbBook = ThisWorkbook
Set wsSheet = wbBook.Worksheets(1)
Set rnReport = wsSheet.Range("D2:D7")
'Initialize the Word objets.
Set wdApp = New Word.Application
Set wdDoc = wdApp.Documents.Open(stPathTemplate)
Set wdbmRange = wdDoc.Bookmarks("Report").Range
'If the macro has been run before, clean up any artifacts before trying to paste the table in again.
On Error Resume Next
With wdDoc.InlineShapes(1)
.Select
.Delete
End With
On Error GoTo 0
'Turn off screen updating.
Application.ScreenUpdating = True
With wdDoc
.Visible = True
.Documents.Open (stPathTemplate)
.Activate
With .ActiveDocument.Content.Find
.ClearFormatting
.Replacement.ClearFormatting
For i = 0 To UBound(Split(StrFind, ",")) 'Loop to replace all the defined dynamic strings
.Text = Split(StrFind, ",")(i)
.Replacement.Text = Split(StrRepl, "*")(i)
.Execute Replace:=wdReplaceAll
Next i
.Forward = True
.Wrap = 1 'FindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=2 'wdReplaceAll (WdReplace Enumeration)
End With
End With
'Copy the report to the clipboard.
rnReport.Copy
'Select the range defined by the "Report" bookmark and paste in the report from clipboard.
With wdbmRange
.Select
.Paste
End With
'Save and close the Word doc.
With wdDoc
'.Save
.SaveAs2 Filename:=stPathSave, _
FileFormat:=wdFormatXMLDocument, AddToRecentFiles:=False
.Close
End With
'Quit Word.
wdApp.Quit
'Null out your variables.
Set wdbmRange = Nothing
Set wdDoc = Nothing
Set wdApp = Nothing
'Clear out the clipboard, and turn screen updating back on.
With Application
.CutCopyMode = False
.ScreenUpdating = True
End With
MsgBox ("Done")
End Sub
I have used the VBA macro below to put multiple tables from multiple Word documents into one worksheet in Excel.
I want the multiple tables from each different Word doc to go into different worksheets with the worksheets named the name of the Word doc.
Sub ImportWordTable()
Dim WordApp As Object
Dim WordDoc As Object
Dim arrFileList As Variant, FileName As Variant
Dim tableNo As Integer 'table number in Word
Dim tableStart As Integer
Dim tableTot As Integer
Dim Target As Range
'On Error Resume Next
arrFileList = Application.GetOpenFilename("Word files (*.doc; *.docx),*.doc;*.docx", 2, _
"Browse for file containing table to be imported", , True)
If Not IsArray(arrFileList) Then Exit Sub '(user cancelled import file browser)
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True
Range("A:AZ").ClearContents
Set Target = Range("A1")
For Each FileName In arrFileList
Set WordDoc = WordApp.Documents.Open(FileName, ReadOnly:=True)
With WordDoc
tableNo = WordDoc.tables.Count
tableTot = WordDoc.tables.Count
If tableNo = 0 Then
MsgBox WordDoc.Name & " contains no tables", vbExclamation, "Import Word Table"
ElseIf tableNo > 1 Then
tableNo = InputBox(WordDoc.Name & " contains " & tableNo & " tables." & vbCrLf & _
"Enter the table to start from", "Import Word Table", "1")
End If
For tableStart = 1 To tableTot
With .tables(tableStart)
.Range.Copy
'Target.Parent.PasteSpecial Format:="Text", Link:=False, DisplayAsIcon:=False
Target.Activate
ActiveSheet.Paste
Set Target = Target.Offset(.Rows.Count + 2, 0)
End With
Next tableStart
.Close False
End With
Next FileName
WordApp.Quit
Set WordDoc = Nothing
Set WordApp = Nothing
End Sub
Try the following macro. It allows you to choose the source folder. It creates a new worksheet for each document and outputs all tables from that document one below the other, with an empty row in between. Except for text wrapping, table formatting is preserved as much as possible.
Sub GetTableData()
'Note: this code requires a reference to the Word object model.
'See under the VBE's Tools|References.
Application.ScreenUpdating = False
Dim wdApp As New Word.Application, wdDoc As Word.Document, wdTbl As Word.Table
Dim strFolder As String, strFile As String, WkBk As Workbook, WkSht As Worksheet, r As Long
strFolder = GetFolder: If strFolder = "" Then GoTo ErrExit
Set WkBk = ActiveWorkbook
'Disable any Word Alerts
wdApp.DisplayAlerts =wdAlertsNone
'Disable any auto macros in the documents being processed
wdApp.WordBasic.DisableAutoMacros
strFile = Dir(strFolder & "\*.doc", vbNormal)
While strFile <> ""
Set wdDoc = wdApp.Documents.Open(Filename:=strFolder & "\" & strFile, ReadOnly:=True, AddToRecentFiles:=False, Visible:=False)
Set WkSht = WkBk.Sheets.Add
WkSht.Name = Split(strFile, ".doc")(0)
With wdDoc
For Each wdTbl In .Tables
With wdTbl.Range.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "[^13^l]"
.Replacement.Text = "¶"
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchWildcards = True
.Execute Replace:=wdReplaceAll
End With
r = WkSht.Cells(WkSht.Rows.Count, 1).End(xlUp).Row
If r > 1 Then r = r + 2
wdTbl.Range.Copy
WkSht.Paste Destination:=WkSht.Range("A" & r)
Next
WkSht.UsedRange.Replace What:="¶", Replacement:=Chr(10), LookAt:=xlPart, SearchOrder:=xlByRows
.Close SaveChanges:=False
End With
strFile = Dir()
Wend
ErrExit:
wdApp.Quit
Set wdDoc = Nothing: Set wdApp = Nothing: Set WkSht = Nothing: Set WkBk = Nothing
Application.ScreenUpdating = True
End Sub
Function GetFolder() As String
Dim oFolder As Object
GetFolder = ""
Set oFolder = CreateObject("Shell.Application").BrowseForFolder(0, "Choose a folder", 0)
If (Not oFolder Is Nothing) Then GetFolder = oFolder.Items.Item.Path
Set oFolder = Nothing
End Function
Something like the following, perhaps. Since I can't replicate your documents my test environment wasn't identical...
The following code declares a Word.Table and a Excel.Worksheet object to the list of declared variables.
The Worksheet object is set to ActiveSheet and later to each added worksheet. Using an object instead of a selection or "active" something is almost always preferable - then it's clearer for both human and VBA what's is meant. ws is also used to more exactly define the Range specifications.
Before looping the tables, the worksheet Name is set to the value stored in Filename for the Word document.
The Table object is set to the WordDoc.tables(tableStart) table. It's more efficient to work with an object instead of querying the full "path" to an object each time. It's also easier to read.
Before looping to the next Word document a new worksheet is added.
Sub ImportWordTable()
Dim WordApp As Object
Dim WordDoc As Object
Dim tbl As Object
Dim arrFileList As Variant, FileName As Variant
Dim tableNo As Integer 'table number in Word
Dim tableStart As Integer
Dim tableTot As Integer
Dim ws As Worksheet
Dim Target As Range
'On Error Resume Next
arrFileList = Application.GetOpenFilename("Word files (*.doc; *.docx),*.doc;*.docx", 2, _
"Browse for file containing table to be imported", , True)
If Not IsArray(arrFileList) Then Exit Sub '(user cancelled import file browser)
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True
Set ws = ActiveSheet
ws.Range("A:AZ").ClearContents
For Each FileName In arrFileList
Set WordDoc = WordApp.Documents.Open(FileName, ReadOnly:=True)
With WordDoc
tableNo = WordDoc.tables.Count
tableTot = WordDoc.tables.Count
If tableNo = 0 Then
MsgBox WordDoc.Name & " contains no tables", vbExclamation, "Import Word Table"
ElseIf tableNo > 1 Then
tableNo = InputBox(WordDoc.Name & " contains " & tableNo & " tables." & vbCrLf & _
"Enter the table to start from", "Import Word Table", "1")
End If
ws.Name = FileName
For tableStart = 1 To tableTot
Set Target = ws.Range("A1")
Set tbl = .tables(tableStart)
With tbl
.Range.Copy
'Target.Parent.PasteSpecial Format:="Text", Link:=False, DisplayAsIcon:=False
Target.Activate
ws.Paste
Set Target = Target.Offset(.Rows.Count + 2, 0)
End With
Next tableStart
.Close False
End With
Set ws = ws.Parent.Worksheets.Add
Next FileName
ws.Delete 'the last sheet is one too many
WordApp.Quit
Set WordDoc = Nothing
Set WordApp = Nothing
End Sub
I'm trying to copy a content from excel into a bookmark in MS word. But I'm getting run time error 424. Kindly help me with it. I'm very new to Visual basics and programming as well. I have attached my code.
Thanks
Sub WordDoc()
Dim wrdApp As Object
Dim Number As String
Dim wrdDoc As Object
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Open("H:\IP Automation\createDoc.docx")
Number = Worksheets("Sheet1").Range("A2")
Call InsBookmark(ID, Number)
End Sub
Sub InsBookmark(strBMName, strVariable)
If strVariable <> "" Then
If ActiveDocument.Bookmarks.Exists(ID) Then
ActiveDocument.Bookmarks(ID).Select
Selection.Delete
Selection.InsertAfter (strVariable)
End If
End If
End Sub
You shouldn't seperate this into two subs, as the word doc will not persist across them so "ActiveDocument" wont work. just copy the code from the second sub into the first and replace ActiveDocument with wrdDoc
This should work for you. Give it a go and see how you get along.
Sub Export_Table_Word()
'Name of the existing Word doc.
Const stWordReport As String = "Final Report.docx"
'Word objects.
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim wdbmRange As Word.Range
'Excel objects.
Dim wbBook As Workbook
Dim wsSheet As Worksheet
Dim rnReport As Range
'Initialize the Excel objects.
Set wbBook = ThisWorkbook
Set wsSheet = wbBook.Worksheets("PwC Contact Information")
Set rnReport = wsSheet.Range("Table1")
'Initialize the Word objets.
Set wdApp = New Word.Application
Set wdDoc = wdApp.Documents.Open(wbBook.Path & "\" & stWordReport)
Set wdbmRange = wdDoc.Bookmarks("Report").Range
Dim tbl As Table
For Each tbl In wdDoc.Tables
tbl.Delete
Next tbl
'If the macro has been run before, clean up any artifacts before trying to paste the table in again.
On Error Resume Next
With wdDoc.InlineShapes(1)
.Select
.Delete
End With
On Error GoTo 0
'Turn off screen updating.
Application.ScreenUpdating = False
'Copy the report to the clipboard.
rnReport.Copy
'Select the range defined by the "Report" bookmark and paste in the report from clipboard.
With wdbmRange
.Select
.Paste
End With
'Save and close the Word doc.
With wdDoc
.Save
.Close
End With
'Quit Word.
wdApp.Quit
'Null out your variables.
Set wdbmRange = Nothing
Set wdDoc = Nothing
Set wdApp = Nothing
'Clear out the clipboard, and turn screen updating back on.
With Application
.CutCopyMode = False
.ScreenUpdating = True
End With
MsgBox "The report has successfully been " & vbNewLine & _
"transferred to " & stWordReport, vbInformation
End Sub