Avatar of carsRST
carsRST
Flag for United States of America asked on

VBA Word - Sample Code

Looking for 2003 Word VBA example to do the following:

1.  Open an existing Word document
2.  On the 5th line down write "Line 5"
             -Font Size: 14
             -Font: Arial
3.  On line 6 write "Line 6" with no format

Please note the code will be done from OUTSIDE word so don't assume any implied object references.
Microsoft WordVisual Basic Classic

Avatar of undefined
Last Comment
carsRST

8/22/2022 - Mon
GrahamSkan

All text must have some formatting. This ensure that Line 5 has the same font formatting as the line above.

You seem to be aware of Referencing. If you are in another Office application, you only need to add the Microsoft Word Object library.
Sub AddText()
    Dim WdDoc As Word.Document
    Dim wdApp As Word.Application
    Dim bNewInstance As Boolean
    Dim rng  As Range
    
    On Error Resume Next 'supress error for next line
    Set wdApp = GetObject(, "Word.Application")
    On Error GoTo 0
    If wdApp Is Nothing Then
        Set wdApp = CreateObject("Word.Application")
        bNewInstance = True
    End If
    wdApp.Visible = True
    
    Set WdDoc = wdApp.Documents.Open("C:\MyFolder\test.doc")
    
    Set rng = WdDoc.Range.Paragraphs(4).Range
    rng.Collapse wdCollapseEnd
    rng.Text = "Line 6" & vbCr
    rng.Collapse wdCollapseStart
    rng.Text = "Line 5" & vbCr
    rng.Font.Name = "Arial"
    rng.Font.Size = 14
    
    'WdDoc.Close wdSaveChanges
    'If bNewInstance Then
        'wdApp.Quit
    'End If


End Sub

Open in new window

carsRST

ASKER
Thanks.

I'm getting this error...

'5941' the requested member of the collection does not

on this line...

 Set rng = WdDoc.Range.Paragraphs(4).Range
ASKER CERTIFIED SOLUTION
GrahamSkan

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
carsRST

ASKER
>>I inferred from your request that there would be.

sorry - i didn't know it would matter.   I should have been specific.  


Thanks so much for your help!
Your help has saved me hundreds of hours of internet surfing.
fblack61