PDA

View Full Version : [SOLVED:] Simple macro to paste highlighted text



John1984
11-30-2018, 08:12 PM
Hi, I'm trying to write a macro (in Office 2016) that simply pastes "COMMENT - ", except that the word "comment" is highlighted yellow. I've gotten as far as below but haven't been able to figure out how to highlight the string Comment but not the rest. For clarity, I'm not looking to highlight every instance of the string in the document. Any suggestions are greatly appreciated -- I'm just starting to learn. Thanks!


Sub Comment()


Dim Comment As String
Comment = "COMMENT"
Selection.TypeText Text:=Comment & " - "


End Sub

macropod
11-30-2018, 08:59 PM
Sub Comment()
Const Comment As String = "COMMENT - "
With Selection
.Text = Comment
.Words(1).HighlightColorIndex = wdBrightGreen
.Collapse wdCollapseEnd
End With
End Sub

John1984
11-30-2018, 09:35 PM
Thanks! The one part I'm still having difficulty with is having just the word "COMMENT" highlighted, not the spaces, dash or text that follows. I tried the following but the highlighting still remains yellow. Any further suggestions?


Sub Comment()
Const Comment As String = "COMMENT"
With Selection
.Text = Comment
.Words(1).HighlightColorIndex = wdYellow
.Collapse wdCollapseEnd
End With
Options.DefaultHighlightColorIndex = wdNoHighlight
Selection.TypeText Text:=" - "
End Sub

macropod
11-30-2018, 09:46 PM
Try:

Sub Comment()
Dim Rng As Range
Const Comment As String = "COMMENT - "
With Selection
.Text = Comment
Set Rng = .Words(1)
With Rng
.End = .End - 1
.HighlightColorIndex = wdBrightGreen
End With
.Collapse wdCollapseEnd
End With
End Sub

John1984
11-30-2018, 10:20 PM
This is exactly what I needed! Thanks a bunch!