Highlight words in MS Word from Access

cstickman

Registered User.
Local time
Yesterday, 18:56
Joined
Nov 10, 2014
Messages
109
Hello Everyone and Happy Monday,

I am trying to export a form and it is basic now, but in the end it will be populating a table with data from Access. I am trying to highlight one sentence when it exports to Word. I cannot figure it out after many Google searches. This is my first time trying to use highlights.

I would like the following sentence to be highlighted yellow - "Please provide the information requested below by 9/14/16."

Code:
Private Sub cmdgenerate_Click()
Dim docWord As Word.Document
Dim rngCurrent As Word.Range
Dim tableWord As Word.Table
Const wdWord9TableBehavior = 1
Const wdAutoFitFixed = 2

Set appword = New Word.Application
appword.Visible = True
Set docWord = appword.Documents.Add()
Set rngCurrent = docWord.Content
With rngCurrent
.InsertAfter "Please provide the information requested below by 9/14/16."
.InsertAfter vbCrLf
.InsertAfter Date
.InsertParagraphAfter
.Collapse Direction:=wdCollapseEnd
End With
Set tableWord = docWord.Tables.Add(rngCurrent, 20, 2, wdWord9TableBehavior, wdAutoFitFixed)
With tableWord
.Cell(1, 1).Range.Text = "Resource"
.Cell(1, 2).Range.Text = "Task"
End With

MsgBox "Completed", vbOKOnly
End Sub
 
First place to start with any office automation...

Record a marco in the application (in this case Word) that does what you want.
Copy the relevant macro code to your VB(A) procedure.

Let us know if you get stuck.

+ I'm pretty sure Word's find or replace has a highlight option.
 
Last edited:
In essence, to get Word to highlight something dynamically through VBA, you must do the following, and I have no code to show you because it has literally been a decade since I last approached this (and the code was owned by my employer anyway).

Create a Word Application Object.

Open your document.

Find the beginning of the text you want to highlight.

Make a selection out of the text from the beginning to the end of what you want to highlight or otherwise visually modify.

Set the properties of the selection. It has been a while so I don't recall offhand, but I believe that you set the .Fill property of the .Font of that selection. I suggest you read up on the COM structure of Word documents to verify that.

At that point, you can do a Save&Close of the document. You don't have to dissolve the selection variable because that goes away when you close the Word App Object.
 

Users who are viewing this thread

Back
Top Bottom