Using excel to add a table in Word document - excel

I'm creating a tool in Excel
Which is going to read in some data and the create a word document based on that data.
So far I've got excel to create the word document and add a few lines of text without any issue.
The next bit though to add a table is causing issues.
I can add the table in fine, but for some reason it deletes the lines of text that I added in the first place.
This is my code:
Dim objWord As Word.Application
Dim objDoc As Word.Document
Dim objSelection As Object
Dim objRange As Object
Dim objTable As Object
Dim ctr as long
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set objDoc = objWord.documents.Add
Set objSelection = objWord.Selection
Set objRange = objDoc.Range
'Adding some heading Text
objSelection.Style = objDoc.Styles("Heading 1")
objSelection.Font.Bold = True
objSelection.TypeText ("Heading Text")
objSelection.TypeParagraph
'Adding some normal Text
objSelection.Style = objDoc.Styles("Normal")
objSelection.Font.Bold = False
objSelection.TypeText ("Normal Text")
objSelection.TypeParagraph
Stop
'Adding the table
objDoc.Tables.Add objRange, 10, 2, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=wdAutoFitWindow
objWord.Quit SaveChanges:=False
Set objWord = Nothing
I put in a stop points after my heading and normal text are added and they appear in the word document fine.(screenshot below)
But as soon as the code reaches the Tables.Add bit, all my text disappears and the document has nothing but the table. (also screenshot below)
I looked around online and tried putting
objSelection.Collapse WdCollapseDirection.wdCollapseEnd
before the Tables.Add line of code, but that didn't help.

Your code to add a table fails because you are adding the table into objRange which you defined as the entire document.
You should also get into the habit of avoiding use of the Selection object, both in Word and Excel. Not only is it ineffecient (the screen has to be redrawn constantly) it is also error prone as the selection could be changed by the user to something you're not expecting.
The code below should work for you.
Dim objWord As Word.Application
Dim objDoc As Word.Document
Dim objRange As Word.Range
Dim objTable As Word.Table
Dim ctr As Long
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set objDoc = objWord.documents.Add
'Adding some heading Text
With objDoc.Paragraphs(1).Range
.Style = objDoc.Styles(wdStyleHeading1)
.Font.Bold = True
.Text = "Heading Text"
.InsertParagraphAfter
End With
'Adding some normal Text
With objDoc.Paragraphs(2).Range
.Style = objDoc.Styles(wdStyleNormal)
.Font.Bold = False
.Text = "Normal Text"
.InsertParagraphAfter
End With
Set objRange = objDoc.Paragraphs.Last.Range
'Adding the table
Set objTable = objDoc.Tables.Add(objRange, 10, 2, _
DefaultTableBehavior:=wdWord9TableBehavior, _
AutoFitBehavior:=wdAutoFitWindow)
objWord.Quit SaveChanges:=False
Set objWord = Nothing

I did the test with the code below and it works :
Pre requisite : add reference "Microsoft Word xx.x Object Library" in your VBA project
Dim WordApp As Word.Application
Dim WordDoc As Word.Document
' create an instance of MS Word
Set WordApp = CreateObject("word.application")
WordApp.Visible = True
Set WordDoc = WordApp.Documents.Add
Range("A1:A2").Copy
WordApp.Selection.TypeText ("Here are my comment")
WordApp.Selection.Paste
' fit the table with window
WordDoc.Tables(1).AutoFitBehavior wdAutoFitWindow
' Save the content into the .doc file
WordDoc.SaveAs2 ("C:\mypath\myDocument.doc")

Related

Inserted Word Table not showing Borders

I can insert a table but the tables borders are not visible. You can see the created document. In order to allow others to run this script I have to use late binding which I suspect may be the cause.
My Code is here:
Sub Button1_Click()
Dim objWord As Object
Dim objDoc
Dim objSelection
Dim i As Long
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add
objWord.Visible = True
Set objSelection = objWord.Selection
objSelection.TypeText ("Insert table after this text")
Set myRange = objDoc.Content
myRange.Collapse Direction:=wdCollapseEnd
objDoc.Tables.Add Range:=myRange, NumRows:=3, NumColumns:=4
Set myTable = objDoc.Tables(1)
With myTable.Borders
.Enable = True
.InsideLineStyle = wdLineStyleSingle
.OutsideLineStyle = wdLineStyleDouble
.InsideColor = wdColorBlack
.OutsideColor = wdColorBlack
End With
End Sub
Here’s your code revised and in my testing it works when I run it from Excel.
Sub Button1_Click()
Dim objWord As Object
Dim objDoc As Object
Dim objSelection As Object
Dim i As Long
Dim myRange As Object
Dim myTable As Object
On Error Resume Next
Set objWord = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Err.Clear
Set objWord = CreateObject("Word.Application")
End If
objWord.Visible = True
On Error GoTo 0
Set objDoc = objWord.Documents.Add
Set objSelection = objWord.Selection
objSelection.TypeText ("Insert table after this text")
Set myRange = objDoc.Content
myRange.Collapse Direction:=wdCollapseEnd
Set myTable = objDoc.Tables.Add(Range:=myRange, NumRows:=3, NumColumns:=4)
With myTable.Borders
.Enable = True
.InsideLineStyle = 1
.OutsideLineStyle = 7
.InsideColor = 0
.OutsideColor = 0
End With
End Sub
The issue with with the table borders not displaying is when using late binding you have to use the numeric values for the setting.
I also made a few other adjustments, they have no impact on the problem you were having, but they are better practices. All objects are declared and I added a test to see if the Word application was already running. In some releases of the Office applications, multiple instances of the application could get loaded into memory when you execute a CreateObject and the application was already there.

Create a word document (from excel) with a title, a paragraph, a table, a paragraph, a text, a paragraph, a table, a paragraph and a text

I am trying to create a word document from excel.
I think I can do it, but to fill the word document with what I want (a title, an empty paragraph, a table... wherever I want) give me some headache. I certainly don't master the word-vba, I find excel-vba easier.
Below is my horrible code, but if you can give me a piece of code doing what is describe in the title, it could be a good starting point for me.
Dim objWord As Object
Dim objDoc As Object
Dim objRange As Object
Dim objTable As Object
Dim txtword As String
'-----------------------
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set objDoc = objWord.Documents.Add
Set objRange = objDoc.Content 'Range
'-----------------------
txtword = "Something"
With objRange
.Text = txtword & vbCr & vbCr 'add the paragraph break at the end of the text string
.Collapse Direction:=0
End With
Set objTable = objDoc.Tables.Add(objRange, 2, 8)
objTable.Borders.Enable = True
objRange.Text = txtword & vbCr & vbCr
objRange.Collapse Direction:=0
' From direct Macro:
'objRange.MoveDown Unit:=wdLine, Count:=3
'objRange.TypeParagraph
'objRange.TypeText Text:="Text"
'objRange.TypeParagraph
' HOW TO GET OUT OF THIS TABLE????
'objRange.Text = "" & vbCr
'Set objRange = objDoc.Content
'objRange.Collapse Direction:=0
objDoc.Tables.Add Range:=objRange, NumRows:=2, NumColumns:=2
'---------------------
Set objTable = Nothing
Set objRange = Nothing
Set objDoc = Nothing
Set objWord = Nothing
To begin with stop using late binding when working across Office applications. There are no advantages to this approach but lots of disadvantages. Instead write your code using the oldest version of Office you need/intend to support.
Secondly, use objDoc.Content.Paragraphs.Last.Range and you’ll have no difficulty building your document.
Thirdly, you should use Styles to format your document so that you can identify which text is a heading, etc. You need to remember to always use the Normal style when inserting tables to enable the correct functioning of table styles, but for other text you should use a Style where the name describes its purpose, i.e. Body Text.
Ideally you would create a template for the type of document you are creating containing any standard content and with all the styles defined as you want them. You can then either go old school and use bookmarks to act as placeholders for text or use content controls.
Sub CreateWordDoc()
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim wdTable As Word.Table
Dim quitWord As Boolean
Dim txtword As String
'-----------------------
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err Then
'Word wasn't already running so create a new instance of MS Word
Err.Clear
Set wdApp = New Word.Application
If Err Then
MsgBox "Microsoft Word not installed"
Exit Sub
Else
'as Word wasn't already open set flag to show Word needs to be shut down
'and make application visible
quitWord = True
wdApp.Visible = True
End If
End If
'clear error stack and reset error handling
On Error GoTo 0
Set wdDoc = wdApp.Documents.Add
'-----------------------
txtword = "Something"
With wdDoc.Content
.Paragraphs.Last.Range.Text = txtword & vbCr & vbCr 'add the paragraph break at the end of the text string
.Paragraphs.First.Style = wdStyleHeading1
Set wdTable = wdDoc.Tables.Add(Range:=.Paragraphs.Last.Range, NumRows:=2, NumColumns:=8)
wdTable.Borders.Enable = True
With .Paragraphs.Last.Range
.Style = wdStyleBodyText
.Text = vbCr & txtword & vbCr
End With
.Paragraphs.Last.Range.Style = wdStyleNormal
Set wdTable = wdDoc.Tables.Add(Range:=.Paragraphs.Last.Range, NumRows:=2, NumColumns:=2)
wdTable.Borders.Enable = True
With .Paragraphs.Last.Range
.Style = wdStyleBodyText
.Text = vbCr & txtword
End With
End With
wdDoc.SaveAs2 "Full path and filename"
'---------------------
If quitWord Then wdApp.Quit
Set wdTable = Nothing
Set wdDoc = Nothing
Set wdApp = Nothing
End Sub

Copy multiple word documents into one new word document

I am new in VBA and would like to asking some help.
I have a list of word document in excel in range B3:B40. I would like to copy the document in the list and paste to a new document without changing the page format.
I already tried the code below, it give me "run time error 13". Can anybody help with this situation?
Thanks in advance for any help.
Application.ScreenUpdating=false
set objword = createobject("Word.Application")
set objdoc = objword.Documents.Add
objword.visible = true
set objselection = objword.Selection
Folderpath = "C:\desktop" 'where I save the word document that would be combined
set objtempword = createobject("Word.Application")
set tempdoc = objword.documents.open (Folderpath & "\" & Sheet1.Range ("B3:B40")
set objtempselection = objtempword.selection
tempdoc.range.select
tempdoc.range.copy
objselection.typeparagraph
objselection.paste
tempdoc.close
I think this could work for you. What was missing is a cycle to work for each file (cell in the range).
Option Explicit
Sub JoinDocs()
Application.ScreenUpdating = False
Dim objword As Object, objdoc As Object, objselection As Object
Set objword = CreateObject("Word.Application")
Set objdoc = objword.Documents.Add
objword.Visible = True
Dim Folderpath As String
Set objselection = objword.Selection
Folderpath = "C:\desktop\" 'where I save the word document that would be combined
Dim vDoc As Variant
Dim objtempword As Object, tempdoc As Object, objtempselection As Object
Set objtempword = CreateObject("Word.Application")
For Each vDoc In Sheet1.Range("B3:B40").Value
Set tempdoc = objword.Documents.Open(Folderpath & vDoc)
Set objtempselection = objtempword.Selection
tempdoc.Range.Select
tempdoc.Range.Copy
objselection.TypeParagraph
objselection.Paste
tempdoc.Close
Next vDoc
End Sub

Copy from Excel to specific location in Word

I'm copying a range of cells from Excel as a picture to a Word document. It pastes at the beginning of the document.
How could I paste in a specific area? The area could be denoted by some text that I'd later find/replace.
Range("A1:H5").Select
Selection.CopyPicture Appearance:=xlScreen, Format:=xlPicture
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open("MyFile.docx")
objWord.Visible = True
Set objSelection = objWord.Selection
objSelection.Paste
End Sub
I just came accross the same problem and used the following code. I use a bookmark called "here" which is saved in my Word document. HTH, Mitch.
Dim WordApp As Word.Application
Dim WordDoc As Word.Document
Set WordApp = New Word.Application
Set WordDoc = WordApp.Documents.Open("MyFile.docx")
Range("A1:H5").Select
Selection.CopyPicture Appearance:=xlScreen, Format:=xlPicture
WordApp.Visible = True
WordApp.ActiveDocument.Bookmarks("here").Select
Set objSelection = WordApp.Selection
objSelection.Paste

Copy context and formatting of a WORD document by VBA code in EXCEL

In EXCEL, I have some VBA codes to open a Word Document A and copy its content from certain page to a new document. Currently, I can copy its text. I am wondering how to copy both context and formatting. Below is my current code and I appreciate any suggestions!
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add
objWord.Visible = True
Set objSelection = objWord.Selection
'Prepare Document B
objDoc.SaveAs (Folderpath to Document B)
Set objTempWord = CreateObject("Word.Application")
Set tempDoc = objWord.Documents.Open(Folderpath to Document A)
'copy context from Document A
With tempDoc.Application
.Selection.GoTo What:=wdGoToPage, Which:=wdGoToAbsolute, Name:="2"
.Selection.EndKey Unit:=wdStory, Extend:=wdExtend
.Selection.Copy
End With
objSelection.TypeParagraph
objSelection.Paste
objSelection.InsertBreak Type:=wdSectionBreakNextPage
tempDoc.Close
objDoc.Application.Statusbar = False
objDoc.Save
This here does the same, without the superfluous extra Application object and without the use of Selection:
Dim objWord As Word.Application
Dim objDoc As Word.Document, newDoc As Word.Document
Dim r As Word.Range, r2 As Word.Range
Set objWord = CreateObject("Word.Application") 'or Set objWord = new Word.Application
Set objDoc = objWord.Documents.Open(FolderpathToDocumentA)
Set newDoc = objWord.Documents.Add
newDoc.SaveAs FolderpathToDocumentB
Set r = objDoc.GoTo(what:=wdGoToPage, which:=wdGoToAbsolute, Name:=2)
r.End = objDoc.Range.End
'copy context from Document A
r.Copy
newDoc.Content.InsertBreak Type:=wdSectionBreakNextPage
newDoc.Range(newDoc.Content.Start, newDoc.Content.Start).Paste
newDoc.Content.InsertBefore vbCrLf
newDoc.Save
objWord.Quit
Does that do what you need?

Resources