简体   繁体   中英

Insert formatted text in word document with VBA Userform

I have a userform which contains some textboxes and a button.

when button is pressed it insert text at the end of the document. however I need to insert the text as following format:

  1. First line bold - textbox1
  2. Second line is a web link so it should be converted into hyperlink ie blue, underline - textbox2
  3. Thrid line is simple text not bold. - textbox3 & 4

the following code does insert the text but not formatted as required. how do I insert the text with least code possible?

Private Sub CommandButton2_Click()
    
    Dim CR As Range
    
    Selection.EndKey wdStory
    
    Set CR = Selection.Range
    
    CR.Text = vbCr & TextBox1.Text _
    & vbCr & TextBox2.Text _
    & vbCr & TextBox3.Text & " at " & TextBox4.Text

End Sub

Possible formatting:

在此处输入图像描述

FINAL EDIT - two lines of code to add

If you truly want to make the new code as short as possible

CR.Paragraphs(CR.Paragraphs.Count - 2).Range.Sentences(1).Font.Bold = True
CR.Paragraphs(CR.Paragraphs.Count - 1).Range.Hyperlinks.Add _
    CR.Paragraphs(CR.Paragraphs.Count - 1).Range, _
    CR.Paragraphs(CR.Paragraphs.Count - 1).Range.Text

For example:

With ActiveDocument.Range
    With .Characters.Last
      .Style = wdStyleStrong
      .Text = TextBox1.Text & vbCr
    End With
    .Characters.Last.Font.Reset
    .Hyperlinks.Add Anchor:=.Characters.Last, Address:=TextBox2.Text
    .Characters.Last.Text = vbCr & TextBox3.Text & " at " & TextBox4.Text
End With

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