1
votes

I am using comptypes to call function and create ms-word document. Being the first time writing such a program there is something I don't understand right, what I want to do is:

  • Create section in the document and call them A, B, ...
  • In each section create paragraphs that contain text. For section A call the paragraphs a1,a2,a3,...
  • Add formatting to each paragraph in each section, the formatting may be different for each paragraphs

Below is some code fragments in VBA, VBA is used since the translations to use comptypes are almost directly and there are more examples on the net for VBA.

Set myRange = ActiveDocument.Range(Start:= ...., End:= ...) //start and end can be any thing 
ActiveDocument.Sections.Add Range:=myRange  //Section A
Set newRange = ActiveDocument.Range(Start:= ...., End:= ...) //start and end can be any thing 
newRange.Paragraphs.Add

I get stuck to select paragraphs a1 and set its text. What is missing for me is a function that say get collection of paragraphs in section A.

1

1 Answers

1
votes

The following VBA, based on the code in the question, illustrates getting a Document object, adding a Section, getting the Paragraphs of that Section, getting the Paragraphs of any given Section in a document, getting the first or any Paragraph from a Paragraphs collection.

Set doc = ActiveDocument   //More efficient if the Document object will be used more than once
Set section1 = doc.Sections.Add(Range:=myRange)  //Section A | Type Word.Section
Set section1Paras = section1.Paragraphs  //Type Word.Paragraphs
//OR
Set sectionParas = doc.Sections(n).Paragraphs //where n = section index number
Set para = sectionParas.First //OR =sectionParas(n) where n= paragraph index number