Home > Enterprise >  Insert formatted text in word document with VBA Userform
Insert formatted text in word document with VBA Userform

Time:06-17

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 i.e 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:

enter image description here

CodePudding user response:

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

CodePudding user response:

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
  • Related