Currently, Lord of fear and I are working on an interesting project - we are developing a solution based on the 1C:Enterprise 8.2 platform for a large company. For the tasks set, the possibilities of 1C's are more than enough and we do not regret our choice at all. Actually, further we will not talk about the great and powerful platform 1C: Enterprise.

One of key functions our program - generation of printed forms of various legislative documents (protocols, notices, etc.). On the technical side, everything seems to be simple - you create a standard layout such as a spreadsheet document and start layout. We spent time and quickly threw in all the printing forms. It turned out well, but then the customer demanded to redo the design, and we got into a puddle. The problem was the inability to apply formatting styles to certain words within the same cell. Yes, you can apply a style to an entire cell, but this method did not suit us, because. one cell can contain several words, but somehow only one of them was required to be specially highlighted.

In principle, this problem can be solved by reducing the size of the spreadsheet document cells. In certain cases, such (small) cells are easier to work with, but changing such a high markup too often is also not enough. At least for me.

We thought, we thought, and decided to abandon the typical layouts of the “Spreadsheet Document” type, and use the capabilities of MS Word. The idea was something like this:

1. Create templates for the necessary documents. All template files were created exactly as templates for MS Word. For those not in the know, templates are files with a dot extension. Based on them, you can create new documents.

2. Using OLE technology, create documents and replace pseudo-variables with desired text. Pseudo-variables were formatted as: [VariableName].

3. Depending on the situation, print or save the generated document.

In principle, there are no difficulties, but until this day, both of us had not had to work from 1C:Enterprise with MS Word. Basically, all the layouts of printed forms I created were based on spreadsheet documents, so I had no experience in transferring data from the platform, say, to MS Word / Excel. I had to deal with reading data from Excel often, but never transmitting it.

After playing a couple of tracks with the guitar, we decided to put the long-suffering instrument aside and get to work. After thinking a little and reading help, we sketched out such an example:

//Create a new object of type Word.Application WordApplication = New COMObject("WORD.Application"); //Create a new document based on the template //In the PathKTemplate variable, specify the full path to the template // created by us (dot file extension) NewDocument = WordApplication .Documents.Add(PathKTemplate); //Prepare to searchReplaceContent = NewDocument.content.Find; //Replace the text //In the first parameter of the Execute method, pass the string to be replaced //In the ninth - the string to be replaced with //i.e. in WhatReplace we will pass the name of the variable (for example, [UserName]) //and in the last one - its valueReplaceContent.Execute(WhatReplace,False,True,False,True,False,String(WhatWeReplace)); //Further everything depends on our Wishlist //Saving the document NewDocument.SaveAs(PathToSave); //Print document NewDocument.PrintOut(); //At the end of the work, you need to close the document and Winword itself. This is done //For the Quit method, I pass the value False. This suggests that we do not need to save the completed document. WordApplication.application.Quit(False); Word Application = 0;

Work results

We were completely satisfied with the option of using MS Word to generate elegant printed forms. We spent a couple of hours writing wrapper procedures, and also converted previously created forms to MS Word templates. We were more than satisfied with the result. Everything works smartly and our customer can easily change the templates of output documents without any problems. In case of jambs (well, if the customer accidentally drops the existing templates), we have provided the ability to restore the original template files.

If you decide to apply this approach in your projects, then be extremely careful. The use of all these nyashek requires the presence on the user's computer MS Word. Considering that today many companies are moving to the terrible (IMHO) OpenOffice - applying this method may cause problems. Fortunately, we are lucky in this regard.

Publication - your R ode memo containing code examples for:

1. filling word template data from 1C;
2. filling in Word headers and footers with data from 1C;
3. filling the table in Word with data from 1C;

Beginning of work

In most cases, we are faced with the following task:
Need to open word document, filled with data from 1C.

To do this, we need to prepare a Word document template. Don't confuse this with Word Template, special files Word, which contain document settings for multiple use. We need a regular Word document with *.docx or *.doc extensions. And then place this document in a layout with binary data.

Attempt //Get layout from binary data Template = GetLayout(AdditionalParameters.ContractType); FileName = GetTemporaryFileName(".docx"); Template.Write(FileName); //Create a COM object for working with Word ObjectWord = New COMObject("Word.Application"); ObjectWord.Documents.add(FileName); // In Word, you can open multiple documents in one application, so the Word.Application.Documents Object is a collection open documents. //In our case, the document is always open one DocumentWord = ObjectWord.Application.Documents(1); DocumentWord.Activate(); Exception Report("Error starting application "+ErrorDescription()); End of Attempt; //Of course, getting the COM object should be placed in an attempt. You never know, something goes wrong.

The reader may rightly notice that a modal call is being used and wag their finger at the author. And he will be right.

//Create the structure of document parameters DocumentParameters = PrepareParameterStructure(); //Fill in the document parameters structure Fill inParameterStructure(DocumentParameters);

Let's delve a little into the principles of how Word works ...

Each Word document is divided into sections, which are made up of pages.

For each section, it is possible to create your own numbering of elements, unique headers and footers, and page settings. So, for example, to rotate one of the pages (print as landscape), you need to create a separate section for it.

Each word page divided into several areas:

  • Page header
  • Main text
  • footer

It should be noted that each section can have a unique header for the first page.

//Object, contains all the main text from all sections of the DocumentWord.Content //The object contains a collection of sections of the document DocumentWord.Sections //Each section has its own collection for the headers DocumentWord.Sections(1).Headers //And its own collection for the footers DocumentWord.Sections(1).Footers //At the same time, if the "Unique header and footer for the first page" checkbox is checked, the Headers and Footers collections will contain two elements

Filling in user parameters

When accessing these collections, we can search them and get built-in objects such as tables.

Now we have more or less understood how to access Word areas, we can play around with them and replace our parameters:

//Let's go through all the parameters and replace them in the document For each Parameter From DocumentParameters Loop PerformReplace(DocumentWord.Content, Parameter.Key, Parameter.Value); //Looking for occurrences of the parameter in the header PerformReplace(DocumentWord.Sections(1).Headers.Item(1).Range(), Parameter.Key, Parameter.Value); //Looking for occurrences of the parameter in the footer of the first and subsequent pages PerformReplacement(DocumentWord.Sections(1).Footers.Item(1).Range(), Parameter.Key, Parameter.Value); ExecuteReplace(DocumentWord.Sections(1).Footers.Item(2).Range(), Parameter.Key, Parameter.Value); EndCycle; //Execute find and replace Function ExecuteReplace(Value Object, Parameter, Value) Object.Find.Execute(Parameter,,Value,2) EndFunction

Consider the Execute method in more detail. Its parameters are identical to the dialog box when replacing/search directly from MS Word:

And here are the main parameters (free translation of MSDN help):

  1. Search text - String - Text to replace. The text may contain special options. For example, ^p - paragraph, ^t - tab
  2. Case Sensitivity - Boolean - If true, the search will be case-sensitive
  3. Whole words - Boolean - If true, searches for whole words. Occurrences of words are not taken into account. For example, when searching for the word home, the word home will be omitted.
  4. Use Wildcards - Boolean - If true, the built-in regular expressions are used.
  5. Search Similar - Boolean - If true, the search result will contain similar words
  6. Search all forms - Boolean - If true, then the search result will contain various forms of words.
  7. Search first - Boolean - If true, will be searched from the beginning to the end of the document
  8. Coverage - WdFindWrap - Specifies the search direction
  9. Format - Format - Format of the searched text
  10. Replacement string - String - The string to replace the original text with
  11. Number of replacements - WdReplace - Determines how many times to replace
  12. etc.

WdReplace - Constant Value:
wdReplaceAll 2
wdReplaceNone 0
wdReplaceOne 1

This method does not allow you to get the "Replacement string" as a selection, but it works about 10 times slower. To get the selected area, you can use a slightly corrected typical function:

//PrintControlMSWordClient with minor changes for SCP configuration 1.3 Function PerformReplace(Value Object, Parameter, Value) SearchString = "[" + Parameter + "]"; StringReplacement = String(Value); //It is necessary to select the areas in which we are replacing Object.Select(); //Get the selected area Selection = Object.Application.Selection; //Find all occurrences of the parameter and replace it with the value we need FindObject = Selection.Find; FindObject.ClearFormatting(); While FindObject.Execute(SearchString) Loop If EmptyString(ReplacementString) Then Selection.Delete(); Else Selection.TypeText(ReplacementString); EndIf; EndCycle; //Deselect selection Selection.Collapse(); EndFunctions

Having already received the selected area, you can edit the text style, font, etc.

//Editing the font Selection.Font //Editing the color Selection.HighlightColorIndex

There is also a second approach that uses the Word object as fields. I don't really like him, because. in large documents, about 100 pages, these fields start to fail (disappear, do not substitute the desired values) and other nonsense. Well, at least in Word 2007. But I'll give it anyway:

When preparing a template, it is necessary to insert fields with the DOCVARIABLE type into the body of the document (you can insert them using the hot keys Ctrl+F9).

These fields can be accessed in the following simple way:

DocumentWord.Variables.Item(ParameterName).Values

Filling tables according to a template

So, we filled in the parameters in the main text of the document, replaced the parameters in the headers and footers, but we still have one trouble - we need to fill in the table.

The approach described below is only suitable for tables with a known format. Those. we can format the table and its rows in any way we want. But then change is quite problematic.

Tables can be accessed through document regions.

//Get access to the first table in the main text Table = DocumentWord.Content.Tables(1)

To set the formatting, it is easier to create a table in the template with an empty first row, which we will delete later.

//Data to fill ParametersPM = DocumentParameters.ApplicationPM; //Need to leave the header and the first line untouched Iterator = 2; Table = DocumentWord.Content.Tables(3); For Each Row From ParametersTCH Loop //By default adds a row above the first Table.Rows.Add(); Fill in the Table Row (Table, Iterator, String, "PP, Nomenclature Name, Unit of Measurement, Price Row", Parameters PM); Iterator = Iterator + 1; EndCycle; //The structure of the templates contains the names of the columns and their order Procedure FillTableRow(Table,RowNumber,FillValue,TemplateStructure,ValueTable) StringArray = General Purpose.ExpandStringIntoSubstringArray(TemplateStructure,","); iterator = 1; For Each String From Array Of Strings Loop If ValueTable.Columns.Find(String) = Undefined AND String<>"PP" Then Iterator = Iterator + 1; Proceed; //Don't forget that the Header is also a string, and when numbering we need to exclude it ElseIf String = "PP" Then Table.Cell(LineNumber, Iterator).Range().Text = String(LineNumber-1); Iterator = Iterator + 1; Proceed; EndIf; Table.Cell(RowNumber, Iterator).Range().Text = String(FillValue[String]); Iterator = Iterator + 1; EndCycle; EndProcedure

That's basically it. I tried to highlight the main issues that arise when working with Word. I hope this review will help you in your work =)

Thanks for the advice and comments:
,

Criticism is only welcome. The more comments, the better the guide will be =)

In the work of a 1C programmer, this functionality is required extremely rarely, although thanks to it you can solve quite challenging tasks with dynamic and non-permanent printing forms. When implementing this task, the work of creating Word templates and placing bookmarks in the Word template is assigned to 1C users.

AT this example it will be shown how, using the mechanisms of 1C and a Word document as a template, you can create a printable form for outputting data to users of the 1C program.

Let's create a template based on a Word document for 1C. First you need to enable bookmarks for more convenient operation with document:


Next, you need to add text and a couple of bookmarks to the template file for 1C. The bookmark is added through the menu "Insert" - "Bookmark". You need to select the bookmark text, copy it, open the "Insert - Bookmark" menu, paste the copied bookmark text and click "Add":


When the Word template file is ready, we create a new external processing in 1C, add a form and insert the following code in the form module: &On the Client Procedure On Opening (Rejection) Fill Word Template (); EndProcedure &AtClient Function FillTemplateWord() //Attempt to create COM object AttemptWordObject = New COMObject("Word.Application"); Exception Report("Error while starting Microsoft Word: " + ErrorDescription(), MessageStatus.Attention); Return Undefined; EndTry; //Path to the template WordObject.Documents.Add("C:\Users\Konstantin\Desktop\Template.docx"); WordTemplate = WordObject.ActiveDocument; //Get all bookmarks from the template For each BookmarkWord From TemplateWord.Bookmarks Loop Report(BookmarkWord.Name); EndCycle; //Replace bookmark1 with text TemplateWord.Bookmarks("Bookmark1").Select(); TemplateWord.Application.Selection.TypeText ("Text for bookmark #1."); //Replace bookmark2 with text TemplateWord.Bookmarks("Bookmark2").Select(); TemplateWord.Application.Selection.TypeText("Text for bookmark #2."); // Change bookmark 3 to current date TemplateWord.Bookmarks("Bookmark3").Select(); TemplateWord.Application.Selection.TypeText(CurrentDate()); ObjectWord.Application.Visible = True; ObjectWord.Activate(); //Closing the document //Word object.Application.Quit(); EndFunctions

As a result of launching external processing 1C to form a printed form based on a template in the form of a Word file, we will get the following result:

Information on the COM methods of the Word object, as well as additional data, can be found on MSDN.

Addition to the note Using Word templates in 1C

I express my gratitude to all those who comment on the record, thanks to you, the material is supplemented with new data and will be useful to a wider range of visitors.

1. And how to change the font size in the inserted text?
It is enough to change the font size of the bookmark in the template. But if you need to dynamically change the dimension, then:

//Replace bookmark3 with the current date TemplateWord.Bookmarks("Bookmark3").Select(); TemplateWord.Application.Selection.Font.Bold = 1; TemplateWord.Application.Selection.Font.Size = 20; TemplateWord.Application.Selection.TypeText(CurrentDate());

2. Is it possible to upload pictures to a template?
Oh sure. Examples for C# and VB are described at the link: https://msdn.microsoft.com/ru-ru/library/ms178792.aspx , and for 1C the code will be as follows:

// Insert image TemplateWord.Bookmarks("Bookmark3").Select(); TemplateWord.Application.Selection.InlineShapes.AddPicture("C:\Users\Konstantin\Desktop\logo_1c.png");

3. When executing the code: ObjectWord.Documents.Add("C:/Template.docx") (where I placed your document) I get an error: "Error calling context method (Add)" What could be the reason?
Maybe try changing the path to: "C:\Template.docx".

4. Please tell me why when saving the layout of the active document type to the word file with the code:

ProcessingObject = FormAttributeToValue("Object"); Layout = ProcessingObject.GetLayout("Delay Letter Template"); FileName = TempFileDirectory() + "\"file.doc";Layout.Write(FileName);

I get instead of a normal document like this http://prntscr.com/eshgjk
I assume that the Write(,) method, by default, writes the file in MXL format. Try setting the value as the second parameter: SpreadsheetDocumentFileType.DOCX, described in more detail in the "Syntax Helper".

5. I have links in my document to files located on network drive. How to make a hyperlink to these files in the template?
An interesting question, if you try to record a macro and see the result, then in Visual Basic adding a hyperlink would look like this:

Sub Macro1() " " Macro1 Macro " " Selection.MoveLeft Unit:=wdCharacter, Count:=15, Extend:=wdExtend ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:= _ "C:\Users\Konstantin \Desktop\Test.txt", SubAddress:="", ScreenTip:="", _ TextToDisplay:="TestLink" End Sub

Add method description on MSDN: https://msdn.microsoft.com/en-us/vba/word-vba/articles/hyperlinks-add-method-word

Accordingly, the code for 1C is as follows:

Function FillTemplateWord() //Attempt to create a COM object Attempt WordObject = New COMObject("Word.Application"); Exception Report("Error starting Microsoft Word: " + ErrorDescription(), MessageStatus.Attention); Return Undefined; End of Attempt; //Path to the template ObjectWord.Documents.Add("C:\Users\k.blagin\Desktop\Template.docx"); TemplateWord = ObjectWord.ActiveDocument; //Get all links from the template For each BookmarkWord From TemplateWord.Hyperlinks Notify Loop(BookmarkWord.Name); EndCycle; //Change the address of an existing link TemplateWord.Hyperlinks("Logs.zip").Address = "C:\Users\k.blagin\Desktop\Memory.zip"; //Replace the bookmark with a link ObjectBookmark = TemplateWord.Bookmarks("Bookmark3"); TemplateWord.Hyperlinks.Add(ObjectBookmark.Range, "C:\Users\k.blagin\Desktop\Template.docx", "", "Template.docx", "C:\Users\k.blagin\Desktop\Template. docx"); ObjectWord.Application.Visible = True; ObjectWord.Activate(); //Closing the document //Word object.Application.Quit(); EndFunctions

Very useful external processing for all typical 1C:Enterprise 8.3 configurations, allows you to generate a Word file according to the selected template from directories and documents of the system. With its help, you can print various specifications, labor contracts and contracts with contractors, warranty cards and so on from 1C. Having at hand Word of the desired structure and slightly modifying it, you will be able to form it directly from 1s with filling in all the necessary parameters.

The processing principle is as follows:

  • select Word of the desired structure,
  • in those places of the file where you need to insert information from 1C, we make bookmarks,
  • after preparing the template, add it to 1C (Files directory),
  • configure the filling of the print template in 1C,
  • we print the necessary documents / directories by selecting the created template.

Preparing the Word template

To demonstrate the work of processing, we will set up printing of the specification for the contract from the document Sales of goods and services. Let's say we have a Word like this:

From it we will form a full-fledged specification. We start by inserting bookmarks in those places where it is necessary to substitute information from the database:



Spaces cannot be used in bookmark names.

When printing, we will also fill in the table of goods. To make it look nice, leave the header and one empty line:


Save Word, close.

Setting up the template filling

Now in the program we open the magazine of sales documents, go to the print menu and press the button to set up printing according to the Word template:


Template customization is available only to users with full rights.

In the settings window that opens, first create new file in the program (meaning the reference element Files) and bind our Word to it:


In the window that opens, select to add a file:


Then select it in the template settings. After that, the bookmarks table is filled in, we need to select the sources for filling in the data in these bookmarks:


The details of the sales document itself, as well as derivatives of these details, are used as a source:

When printing, you can also use additional details of directories and documents.

The list of available details is very large, it is convenient to use the quick input:


As a result of source selection, the table will look like this:


For the value to the rows of the table, case declension is available, as well as the abbreviation of the full name:


To print a table in Word, select the original document table:


After selecting a table, help appears with the names of those details that can be used to display the table in Word. It remains for us to list the necessary details separated by commas (in the order of the file columns). It is allowed to leave an empty value in the column or write arbitrary text there:


Everything is OK, now we can print the desired Word.

Printing according to a customized template is now available to everyone, i.e. users do not need to each set up printing on their own.



We can print both a single document and a list:


On the print settings form, in addition to creating new templates, you can edit existing ones:


In the event that several Word templates are configured for the object, then when you select the print command, a window will open with the choice of the required one:


To avoid conflicts with user access rights to the directory Files you need to install, in addition to the print processing itself in Word, also an extension for 1C (located in the same archive with processing), which will provide users with access to read the reference book.

If you have any questions / comments / suggestions on this processing, I will be happy to answer.

Release 1.1.2.2 dated 12/15/2018

To display the date when printing a template, the ability to select a format has been added; in the tabular part, in addition to the nomenclature, you can now specify the article and unit of measure:


Now you can remove unnecessary templates:


Release 1.1.2.3 dated 01/29/2019

Now you can display parts of the date separately - day, month (number or name) and year:


For individuals(and contractors with the type of individual) you can now display passport data:


Release 1.1.2.4 dated 03/12/2019

When printing in Word the tabular part of the goods movement documents, it became possible to use not only the details of this tabular part, but also any details of the nomenclature:


Release 1.1.2.5 dated 07/12/2019

It became possible not only to generate a Word template, but also to automatically attach it to the source object (to attached files). To do this, select the setting option Save to attached files.


At the end of the printing procedure, the attached file form will open.


From this form, if necessary, you can open a completed Word template for viewing / editing.

This article is an attempt to collect information on the work (on entry level) with MS Word in one place. There is a lot of similar material, and with the proper perseverance, all this can be found. I wanted to collect the main points in one place.

The publication is a kind of memo containing code examples for:

  1. filling the Word template with data from 1C;
  2. filling Word headers and footers with data from 1C;
  3. filling a table in Word with data from 1C;
Beginning of work

In most cases, we are faced with the following task:
You need to open a Word document filled with data from 1C.

To do this, we need to prepare a Word document template. Don't confuse this with Word Template, special Word files that contain document settings for reuse. We need a regular Word document with *.docx or *.doc extensions. And then place this document in a layout with binary data.

Attempt
//Get layout from binary data
Template = GetLayout(AdditionalParameters.ContractType);
FileName = GetTemporaryFileName(".docx");
Template.Write(FileName);
//Create a COM object to work with Word
WordObject = New COMObject("Word.Application");
ObjectWord.Documents.add(FileName);
//Word can have multiple documents open in the same application, so the Word.Application.Documents Object is a collection of open documents.
//In our case, the document is always open alone
DocumentWord = ObjectWord.Application.Documents(1);
DocumentWord.Activate();
Exception Report("Error starting application "+ErrorDescription());
End of Attempt;
//Of course, getting the COM object should be placed in an attempt. You never know, something goes wrong.

The reader may rightly notice that a modal call is being used and wag their finger at the author. And he will be right.

//Create the document parameters structure
DocumentParameters = PrepareParameterStructure();
//Fill in the document parameters structure
Fill inStructureParameters(DocumentParameters);

Let's delve a little into the principles of how Word works ...

Each Word document is divided into sections, which are made up of pages.

For each section, it is possible to create your own numbering of elements, unique headers and footers, and page settings. So, for example, to rotate one of the pages (print as landscape), you need to create a separate section for it.

Each Word page is divided into several areas:

  • Page header
  • Main text
  • footer
It should be noted that each section can have a unique header for the first page.

//Object, contains all the main text from all sections of DocumentWord.Content
//Object contains a collection of document sections
DocumentWord.Sections
// Each section has its own collection for headers
DocumentWord.Sections(1).Headers
//And own collection for footers
DocumentWord.Sections(1).Footers
//At the same time, if the "Unique header for the first page" checkbox is checked, then the Headers and Footers collections will contain two elements

Filling in user parameters

When accessing these collections, we can search them and get built-in objects such as tables.

Now we have more or less understood how to access Word areas, we can play around with them and replace our parameters:

//Iterate through all the parameters and replace them in the document
For Each Parameter From DocumentParameters Loop
ExecuteReplace(DocumentWord.Content, Parameter.Key, Parameter.Value);
//Looking for occurrences of the parameter in the header
ExecuteReplace(DocumentWord.Sections(1).Headers.Item(1).Range(), Parameter.Key, Parameter.Value);
//Look for parameter occurrences in the footer of the first and subsequent pages
ExecuteReplace(DocumentWord.Sections(1).Footers.Item(1).Range(), Parameter.Key, Parameter.Value);
ExecuteReplace(DocumentWord.Sections(1).Footers.Item(2).Range(), Parameter.Key, Parameter.Value);
EndCycle;

//Perform find and replace Function
PerformReplace(Value Object, Parameter, Value)
Object.Find.Execute(Parameter,,Value,2)
EndFunctions

Consider the Execute method in more detail. Its parameters are identical to the dialog box when replacing/search directly from MS Word:

(36.38 kilobytes) Number of downloads: 5

And here are the main parameters (free translation of MSDN help):

  1. Search text - String - Text to replace. The text can contain special parameters. For example, ^p - paragraph, ^t - tab
  2. Case Sensitivity - Boolean - If true, the search will be case-sensitive
  3. Whole words - Boolean - If true, searches for whole words. Occurrences of words are not taken into account. For example, when searching for the word home, the word home will be omitted.
  4. Use Wildcards - Boolean - If true, the built-in regular expressions are used.
  5. Search Similar - Boolean - If true, the search result will contain similar words
  6. Search all forms - Boolean - If true, then the search result will contain various forms of words.
  7. Search first - Boolean - If true, will be searched from the beginning to the end of the document
  8. Coverage - WdFindWrap - Specifies the direction of the search
  9. Format - Format - Format of the searched text
  10. Replacement string - String - The string to replace the original text with
  11. Number of replacements - WdReplace - Determines how many times to replace
  12. etc.
WdReplace - Constant Value:
wdReplaceAll 2
wdReplaceNone 0
wdReplaceOne 1

This method does not allow you to get the "Replacement string" as a selection, but it works about 10 times slower. To get the selected area, you can use a slightly corrected typical function:

//ManagePrintMSWordClient with minor changes for SCP 1.3 configuration
Function PerformReplace(Value Object, Parameter, Value)
SearchString = "[" + Parameter + "]";
StringReplacement = String(Value);
// It is necessary to select the areas in which we are replacing
Object.Select();
//Get the selected area
Selection = Object.Application.Selection;
//Find all occurrences of the parameter and replace it with the value we need
FindObject = Selection.Find;
FindObject.ClearFormatting();
While FindObject.Execute(SearchString) Loop
If EmptyString(ReplacementString) Then
Selection.Delete();
Otherwise
Selection.TypeText(SubstitutionString);
EndIf;
EndCycle;
// Deselect
Selection.Collapse();
EndFunctions

Having already received the selected area, you can edit the text style, font, etc.

//Editing the font
Selection.Font
//Edit color
Selection.HighlightColorIndex

There is also a second approach that uses the Word object as fields. I don't really like him, because. in large documents, about 100 pages, these fields start to fail (disappear, do not substitute the desired values) and other nonsense. Well, at least in Word 2007. But I'll give it anyway:

When preparing a template, it is necessary to insert fields with the DOCVARIABLE type into the body of the document (you can insert them using the hot keys Ctrl+F9).

These fields can be accessed in the following simple way:

DocumentWord.Variables.Item(ParameterName).Values

Filling tables according to a template

So, we filled in the parameters in the main text of the document, replaced the parameters in the headers and footers, but we still have one trouble - we need to fill in the table.

The approach described below is only suitable for tables with a known format. Those. we can format the table and its rows in any way we want. But then change is quite problematic.

Tables can be accessed through document regions.

//Get access to the first table in the body text
Table = DocumentWord.Content.Tables(1)

To set the formatting, it is easier to create a table in the template with an empty first row, which we will delete later.

//Data to fill
Parameters PM = ParametersDocument.Application PM;
//Need to leave the header and the first line untouched Iterator = 2;
Table = DocumentWord.Content.Tables(3);
For each Row From Parameters PM Loop
//By default adds a line above the first one
Table.Rows.Add();
Fill in the Table Row (Table, Iterator, String, "PP, Nomenclature Name, Unit of Measurement, Price Row", Parameters PM);
Iterator = Iterator + 1;
EndCycle;
//Template structure contains the names of the columns and their order
Procedure FillTableRow(Table,RowNumber,FillValue,TemplateStructure,ValueTable)
StringArray = General Purpose.ExpandStringIntoSubstringArray(TemplateStructure,",");
iterator = 1;
For Each String From Array Of Strings Loop
If ValueTable.Columns.Find(String) = Undefined AND String "PP" Then
Iterator = Iterator + 1;
Proceed;
// Do not forget that the Header is also a string, and when numbering, we need to exclude it
ElseIf String = "PP" Then
Table.Cell(RowNumber, Iterator).Range().Text = String(RowNumber-1);
Iterator = Iterator + 1;
Proceed;
EndIf;
Table.Cell(RowNumber, Iterator).Range().Text = String(FillValue[String]);
Iterator = Iterator + 1;
EndCycle;
EndProcedure

That's basically it. I tried to highlight the main issues that arise when working with Word. I hope this review will help you in your work =)

[you need to register to view the link]