pythonvbams-wordcomtypes

MS word document document stucturre and COM calls and python


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:

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.


Solution

  • 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