1
votes

I am trying to format a Word Document from an Excel Document. I am getting

Runtime Error 5941: The requested member of the collection does not exist.

I am simply trying to style the second paragraph as the Normal built in style. My lack of experience probably shows. The problem seems to be with the paragraph selection, but I'm not entirely sure how to go about it.

Dim WordApp As Word.Application
Set WordApp = New Word.Application

WordApp.Documents.Add Template:="Normal", NewTemplate:=False, DocumentType:=0
WordApp.Visible = True

WordApp.Selection.TypeText ("New Document")

WordApp.Selection.Paragraphs(1).Style = wdStyleHeading1

WordApp.Selection.TypeText vbNewLine & "Date" & Date

WordApp.Selection.Paragraphs(2).Style = wdStyleNormal

End Sub

Edit: I am now trying to find the best way to change format on the same line. For Example:

Date: 10/02/2021

The problem is that so far my style changes apply to a whole paragraph. Any ideas?

2
Have you tried WordApp.ActiveDocument.Paragraphs(2).Style = wdStyleNormal instead? - braX
Thanks, it worked. - Louiee
Whilst using ActiveDocument may work it is bad practice for a whole host of reasons. Best practice is to use a variable as demonstrated in the answer from macropod, i.e. Set WdDoc = .Documents.Add. - Timothy Rylatt

2 Answers

1
votes

Better still:

Sub Demo()
Dim WdApp As New Word.Application, WdDoc As Word.Document
With WdApp
  .Visible = True
  Set WdDoc = .Documents.Add
  With WdDoc
    .Range.Text = "New Document" & vbCr & "Date: " & Date
    .Paragraphs(1).Style = wdStyleHeading1
  End With
End With
End Sub

Note the absence of code to select the Normal template or to apply the Normal Style to the 2nd paragraph. That's because the default template is 'Normal' and the default Style is 'Normal', hence specifying those shouldn't ordinary be necessary. If you wanted a particular default Style for the document as a whole, only to be replaced by headings, etc., apply that via '.Paragraphs(1).Style = ' before '.Range.Text = '.

0
votes

You want to use ActiveDocument instead of Selection:

WordApp.ActiveDocument.Paragraphs(2).Style = wdStyleNormal