Reputation: 75
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?
Upvotes: 1
Views: 1077
Reputation: 13540
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 = '.
Upvotes: 1
Reputation: 11755
You want to use ActiveDocument
instead of Selection
:
WordApp.ActiveDocument.Paragraphs(2).Style = wdStyleNormal
Upvotes: 0