Consulting

Results 1 to 5 of 5

Thread: Simple macro to paste highlighted text

  1. #1

    Simple macro to paste highlighted text

    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

  2. #2
    Knowledge Base Approver VBAX Guru macropod's Avatar
    Joined
    Jul 2008
    Posts
    4,435
    Location
    Sub Comment()
    Const Comment As String = "COMMENT - "
    With Selection
      .Text = Comment
      .Words(1).HighlightColorIndex = wdBrightGreen
      .Collapse wdCollapseEnd
    End With
    End Sub
    Cheers
    Paul Edstein
    [Fmr MS MVP - Word]

  3. #3
    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

  4. #4
    Knowledge Base Approver VBAX Guru macropod's Avatar
    Joined
    Jul 2008
    Posts
    4,435
    Location
    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
    Cheers
    Paul Edstein
    [Fmr MS MVP - Word]

  5. #5
    This is exactly what I needed! Thanks a bunch!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •