Search code examples
vb.netms-wordoffice-interop

VB.NET: Inserting text right after the end of the paragraph


My goal is to create a word doc where in each letter has different fonts. Fonts will be randomly selected. Code seems working but the only problem is that I can't get the letters append right after the previous string. It keeps making new paragraph for each letter.

wp = wd.Content.Paragraphs.Add
wp.selection.Font.Name = font
wp.selection.TypeText = letter

Here's the result

Image 1

Image 2


Solution

  • You probably want to use the selection property over Range.

    Try replacing

    wp.Range.Font.Name = font
    wp.Range.Text = letter
    

    with

    wp.Selection.font.Name = font
    wp.Selection.TypeText letter
    

    Selection will be the current location of the cursor.

    I'm not exactly sure of your intent with wp.Range.InsertParagraphAfter(), but I don't believe it's necessary to be in the For Each . . . Next loop.