Home > OS >  VBA to insert new line in a word document
VBA to insert new line in a word document

Time:04-16

I have the below code to insert lines in a word document. I want to enter 3 blank lines to print Line2. How to code VBA to insert 3 blank lines in a word document so that I can print Line2 after that.

   Line1 = "Line1 hello"
   Line2 = "Line2 hello"
   
   Set objWord = CreateObject("Word.Application")
   Set objDoc = objWord.Documents.Add
   objWord.Visible = True
   
   ' objWord.ActiveDocument.Styles ("Heading 2")
   Set objSelection = objWord.Selection
   objSelection.Font.Bold = True
   objSelection.Font.Name = "Arial"
   objSelection.TypeText (Line1)

CodePudding user response:

Here's one way

Public Sub MakeWordDoc()
    
    Dim wd As Word.Application
    Dim doc As Word.Document
    Dim i As Long
    
    Set wd = New Word.Application
    Set doc = wd.Documents.Add
    wd.Visible = True
    
    doc.Paragraphs.Add.Range.Text = "Line 1 hello"
    
    For i = 1 To 4
        doc.Paragraphs.Add
    Next i
    
    doc.Paragraphs.Add.Range.Text = "Line 2 hello"
    
End Sub

I don't know why I have to add four paragraphs to get three blank lines, but when I add text to the last paragraph, it deletes the blank before it.

Here's another way Public Sub MakeWordDoc()

    Dim wd As Word.Application
    Dim doc As Word.Document
    Dim para As Word.Paragraph
    Dim i As Long
    
    Set wd = New Word.Application
    Set doc = wd.Documents.Add
    wd.Visible = True
    
    Set para = doc.Paragraphs.Add
    para.Range.Text = "Line 1 hello"
    para.Range.ParagraphFormat.SpaceAfter = 18
    
    doc.Paragraphs.Add
    doc.Paragraphs.Add.Range.Text = "Line 2 hello"
    
End Sub

You can make the 18 whatever you want - it's in points. Again, I had to add a blank paragraph for line 2 to eat up, which I don't understand. Hopefully this gives you enough to work out the details on your own.

  • Related