Text after table in Word using VBA codes - excel

I create a Word document using VBA codes and transfer data from Excel to a table I create in the Word document.
I get an error starting a new line/paragraph after the table.
My code selects the whole table but does not start new text after the table, so later content is being added to cell(1,1) in the table.
I am just showing you the structure of my codes and I get an error at the Selection.Collapse line of code.
run time error 438, object doesn't support this property or method.
Sub Word_Report()
Dim objWord As Object
Dim objDoc As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set objDoc = objWord.Documents.Add()
With objWord.Selection
Set myTable = objDoc.Tables.Add(Range:=objWord.Selection.Range, NumRows:=7, NumColumns:=3)
myTable.Borders.Enable = True
''' my table contents'''
end with
'start new line after table
objDoc.Range.InsertAfter Chr(13) & "Hello"
.Font.Size = 11
.BoldRun
End sub

Edited
Try the following:
Sub Word_Report()
Dim objWord As Object
Dim objDoc As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set objDoc = objWord.Documents.Add()
With objWord.Selection
Set myTable = objDoc.Tables.Add(Range:=objWord.Selection.Range, NumRows:=7, NumColumns:=3)
myTable.Borders.Enable = True
''' my table contents'''
End With
'start new line after table
objDoc.Range.InsertAfter Chr(13) & "Hello"
End Sub
Use .Range instead of Selection

To insert text immediately following at table, you have to set the range to the table then collapse the range. Insert your table, flow all your data into it, format the table.
When you've got it how you want it, use code like this where h1 is a Word.Range and objTemplate is a Word.Document object:
Set h1 = objTemplate.Tables(TableNum).Range
h1.Collapse Direction:=wdCollapseEnd

Related

Remove part of the border of a table excel VBA

There is a set of forms that we sometimes have to fill out at work, and I'm trying to automate the task by having excel VBA recreate the form as a word document and populate with the appropriate data and print as a pdf. I'm getting stuck on removing the border line style. I want there to be no border line on the left side. I have tried different approaches, and the one that seems the most likely that it should work based on my understanding is below:
(note: ".Border(xlEdgeleft).LineStyle = xlLineStyleNone" is the line that is giving me trouble)
Sub main()
Dim objWord As Object
Dim objDoc As Object
Dim objHdrRange As Object
Dim myTable As Object
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add
Set objHdrRange = objDoc.Sections(1).headers(1).Range
Set myTable = objWord.activedocument.tables.Add(objHdrRange, 5, 5)
With myTable
.Borders.enable = True
.Border(xlEdgeleft).LineStyle = xlLineStyleNone
‘more code goes here later
End With
Set objDoc = Nothing
Set objHdrRange = Nothing
objWord.Quit
End Sub
xlEdgeLeft and xlLineStyleNone are from the Excel Object Model, not from the Word Object Model, and you need the latter.
Since you are late-binding, you could add the following lines:
Const wdBorderLeft As Long = -2
Const wdLineStyleNone As Long = 0
and replace xlEdgeLeft and xlLineStyleNone with these, respectively.
See the WdBorderType and WdLineStyle enum docs for more detail.

Select Word Doc using Excel VBA

I want to create Excel VBA code that asks the user to open a pre-existing Word document with text form fields and input existing Excel data in these form fields.
I have code that writes the Excel data into the Word text form field.
Sub NewMacro()
Dim wdApp As Object, wd As Object, ac As Long, ws As Worksheet
Set ws = Sheets("Tables")
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set wdApp = CreateObject("Word.Application")
End If
On Error GoTo 0
Set wd = wdApp.Documents.Open("C:\Test\Test.docx")
wdApp.Visible = True
With wd
.FormFields("CustomerName").Result = ws.Range("D4").Value
End With
Set wd = Nothing
Set wdApp = Nothing
End Sub
I am lost as to converting the Set wd= wdApp.Documents.Open("FilePath") line into a dialog box.
Does a function exist where the user can select the file by clicking through Windows Explorer as opposed to typing the path?
Do you want the user to input the name of a Word file? Do you want the InputBox method?
Dim strWord As String
strWord = InputBox(prompt:="Type the file path and name of the Word file.", title:="Which file?", default:="C:\Path\File.docx")
Set wd = wdApp.Documents.Open(strWord)
Tell me if I didn't understand your question.

Find and Replace footer text in Word with an Excel VBA Macro

I'm trying to make a macro in Excel which opens a Word document, find a especify text, which is inside of footer in word doc, and replace it for a text.
At the moment, my macro opens the word doc but I couldn't figure out how to get into footer and find those texts.
Dim objWord
Dim objDoc
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open(ThisWorkbook.Path & "/NotaPromissoriaAutomatica.docx")
objWord.Visible = True
The footer have two texts which have to be replaced
1 - VAR_CIDADE > Which will be replaced the current city (which is in A1 of my excel table)
2 - VAR_DATA > Which will be replaced the current date (which is in A2 of my excel table)
I created a test document with a single page, header and footer, with the footer using the keyword "VAR_DATA". The example code below will search for all footers in the document and make the replacement. Notice that the code only searches in Section(1) though. If you have more sections, you may have to create an outer loop to search for each footer in every section.
Option Explicit
Public Sub FixMyFooter()
Dim myWord As Object
Dim myDoc As Word.Document
Set myWord = CreateObject("Word.Application")
Set myDoc = myWord.Documents.Open("C:\Temp\footertest.docx")
Dim footr As Word.HeaderFooter
For Each footr In myDoc.Sections(1).Footers
With footr.Range.Find
.Text = "VAR_DATA"
.Replacement.Text = Format(Now(), "dd-mmm-yyyy")
.Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindStop
End With
Next footr
myDoc.Save
myWord.Quit
End Sub
You'll need to expand the example to find your additional text with your own formatting.

Excel VBA - Cross Referencing Bookmark/Form Field to Word

I have very minimal knowledge about VBA but still learning as it goes.
I've been using bookmarks in the word in order to populate data from excel. However, due to the content that some data need to repeat in a document, I tried using Text Form Field/Bookmark and REF Field to duplicate the same data.
The problem came in when once I populated data to the word, the text form field/bookmark disappear which causes REF Field unable to track the data that was referred to, hence, the "Error! Reference source not found."
In conclusion, what I'm trying to do is to populate data from excel to a locked word document and at the same time to retain Text Field Form/Bookmark in order to let REF field to track and duplicate the same data.
Is there any way to retain the Text Field Form/Bookmark placeholder after data is populated to the word? Here's my code that I am unable to solve in excel VBA.
Appreciate your help in advance!
Private Sub CommandButton1_Click()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Open "C:\Users\" & Environ("username") & "\Desktop\XXX\XXX"
objWord.ActiveDocument.Unprotect Password:="xxx"
With objWord.ActiveDocument
Dim objBMRange As Range
Set objBMRange = .Bookmarks("pr1").Range.Text = ws.Range("C28").Value
objBMRange.Text = pr1
.Bookmarks.Add "pr1", BMRange
.Fields.Update
objWord.ActiveDocument.Protect Password:="xxx", NoReset:=False, Type:=wdAllowOnlyFormFields
End With
Set objWord = Nothing
End Sub
You were almost there. Very near, but you didn't get the Range object sorted out. Please try this code (only partially tested).
Private Sub CommandButton1_Click()
Dim Ws As Worksheet
Dim objWord As Object
Dim Mark As String
Dim Txt As String
Dim BmkStart As Long
Mark = "pr1"
Set Ws = ThisWorkbook.Sheets("Sheet1")
Txt = Ws.Range("C28").Value
Set objWord = CreateObject("Word.Application")
With objWord
.Visible = True
.Documents.Open "C:\Users\" & Environ("username") & "\Desktop\XXX\XXX"
With .ActiveDocument
.Unprotect Password:="xxx"
If .Bookmarks.Exists(Mark) Then
With .Bookmarks(Mark).Range
BmkStart = .Start
.Text = Txt
End With
.Bookmarks.Add Mark, .Range(BmkStart, BmkStart + Len(Txt))
End If
.Fields.Update
.Protect Password:="xxx", NoReset:=False, Type:=wdAllowOnlyFormFields
End With
End With
Set objWord = Nothing
End Sub
One point is that the Bookmark defines a Word.Range (different from an Excel.Range which you get when you specify no application while working in Excel). The other, that Bookmark defines a range but isn't a range itself, not even a Word.Range. Therefore you get or set its text by modifying it's range's Text property.

Copy range in excel, find specific text in MSWord document, replace with clipboard image

I'm copying a range in excel as an image, and I want to insert it into a word document as replacement for dummy text "Qwerty01". Right now it opens the word document and pastes the image at the top - how can I get it to move the cursor to the dummy text before pasting?
Sub automateword()
Dim sheet1 As Object
Dim wdFind As Object
Set wordapp = CreateObject("word.Application")
wordapp.documents.Open ThisWorkbook.Path & "\Word.docx"
wordapp.Visible = True
Set sheet1 = Sheets("Prog General (1)")
Set wdFind = wordapp.Selection.Find
sheet1.Range("D14:N46").CopyPicture Appearance:=xlScreen, Format:=xlPicture
wdFind.Text = "Qwerty01"
wordapp.Selection.Paste
End Sub

Resources