Link to home
Start Free TrialLog in
Avatar of carsRST
carsRSTFlag 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.
Avatar of GrahamSkan
GrahamSkan
Flag of United Kingdom of Great Britain and Northern Ireland image

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

Avatar of 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
Avatar of GrahamSkan
GrahamSkan
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of 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!