简体   繁体   中英

How to add set text bold, italic, super script and sub script in comment text in Word VBA?

I want to format the comment text in Word Template using VBA. I can add simple text using following code. But I don't know how to format the text

CommentText = "Test Bold: Bold Text & vbNewLine & Test Italic: Italic Text & vbNewLine & Test Bold Italic: Bold Italic Text & vbNewLine &  Test Superscript: My BrandTM & vbNewLine & Test Subscript: H2O"
Selection.Comments.Add Range:=Selection.Range
With Selection
        .TypeText (CommentText)                        'Add comment text
End With

Output should be like following Image: 在此处输入图片说明

The code below will add your formatted comment to the selected text. Tested in Word 2007, and functioning as expected.

By the way, in case you need to do something similar in the future, start recording a macro, add your comment, then stop recording. The resulting macro code should get you most of the way there.

Public Sub AddComment()

  Selection.Comments.Add Range:=Selection.Range

  With Selection
    .TypeParagraph

    .TypeText Text:="Test Bold: Bold Text"
    .MoveLeft Unit:=wdCharacter, Count:=9, Extend:=wdExtend
    .Font.Bold = wdToggle
    .EndKey Unit:=wdLine
    .Font.Bold = wdToggle

    .TypeParagraph

    .TypeText Text:="Test Italic: Italic Text"
    .MoveLeft Unit:=wdCharacter, Count:=11, Extend:=wdExtend
    .Font.Italic = wdToggle
    .EndKey Unit:=wdLine
    .Font.Italic = wdToggle

    .TypeParagraph

    .TypeText Text:="Test Bold Italic: Bold Italic Text"
    .MoveLeft Unit:=wdCharacter, Count:=16, Extend:=wdExtend
    .Font.Bold = wdToggle
    .Font.Italic = wdToggle
    .EndKey Unit:=wdLine
    .Font.Italic = wdToggle
    .Font.Bold = wdToggle

    .TypeParagraph

    .TypeText Text:="Test Superscript: My BrandTM"
    .MoveLeft Unit:=wdCharacter, Count:=2, Extend:=wdExtend
    .Font.Superscript = True
    .EndKey Unit:=wdLine
    .Font.Superscript = False

    .TypeParagraph

    .TypeText Text:="Test Subscript: H20"
    .MoveLeft Unit:=wdCharacter, Count:=1
    .MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
    .Font.Subscript = True
    .EndKey Unit:=wdLine
    .Font.Subscript = False
  End With

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM