PDA

View Full Version : VBA code to highlight text in word document



srini4547
07-03-2016, 02:24 AM
Hi,

I am new to VBA scripts

my requirement is ,i want to highlight text in word document based on below conditions

eg: hello how are you ,i am fine

when i passed input as hello and number of characters to be highlight from hello using text box , it should highlight till that range

my input is hello and number of characters to be highlight from hello to till you (12 char count). so it should highlight from hello to you.


Please help me on this.


Thanks

gmayor
07-03-2016, 05:43 AM
That is fairly straightforward using ranges e.g.


Sub Macro1()
Dim oRng As Range
Dim strText As String
strText = InputBox("Text to Find", , "hello")
If strText = "" Then GoTo lbl_Exit
Set oRng = ActiveDocument.Range
With oRng.Find
Do While .Execute(FindText:=strText)
oRng.End = oRng.End + 12
oRng.HighlightColorIndex = wdTurquoise
oRng.Collapse 0
Loop
End With
lbl_Exit:
Set oRng = Nothing
Exit Sub
End Sub

srini4547
07-03-2016, 08:12 AM
Thanks you so much Gmayor...its exact solution for my query