Word текст в скрипт

Как добавить скрипты в документы Word — Вокруг-Дом — 2021

Table of Contents:

Сценарии — это язык программирования, в котором созданные программы представляют собой набор команд, которые выводятся и затем выполняются одна за другой. Чтобы добавить сценарии в Microsoft Word, необходимо использовать дополнение Microsoft Script Editor (MSE). Коллекция Scripts в MSE содержит объекты Script в документе Office. Объект Script представляет пару тегов, ее настройки и весь текст, который находится между парой тегов.Документ Word может содержать множество блоков скриптов, и каждый блок может иметь любое количество процедур.

Вещи, которые вам понадобятся

  • Microsoft Script Editor
  • Microsoft Word

Шаг 1

Откройте Word и откройте редактор скриптов. Это часть Office и включена в Word. Откройте редактор сценариев в Office 2000 или 2003, открыв меню «Сервис», укажите макросы и выберите «Редактор сценариев». Если вы используете Office 2007, нажмите кнопку «Офис» и нажмите «Параметры Excel». Перейдите на вкладку «Популярные» и выберите «Показать вкладку разработчика» на ленте.

Шаг 2

Добавьте скрипт в документ Word. Сделайте это, используя метод «Добавить» из коллекции Scripts. Этот метод использует выборные аргументы, которые могут указывать атрибут идентификатора скрипта, язык, местоположение, дополнительные атрибуты тега и скрипт, который будет содержать себя в «

Создание макросов для упрощения работы с Microsoft Word

Макрос — это набор определенных действий, команд и/или инструкций, которые сгруппированы в одну целостную команду, обеспечивающую автоматическое выполнение той или иной задачи. Если вы активный пользователь MS Word, вы тоже можете автоматизировать часто выполняемые задачи, создав для них соответствующие макросы.

Именно о том, как включить макросы в Ворд, как их создавать и использовать для упрощения, ускорения рабочего процесса и пойдет речь в этой статье. И все же, для начала не лишним будет более подробно разобраться в том, зачем вообще они нужны.

Области использования макросов:

    1. Ускорение часто выполняемых операций. В числе таковых форматирование и редактирование.

2. Объединение нескольких команд в целостное действие “от и до”. Например, с помощью макроса можно вставить таблицу заданного размера с необходимым количеством строк и столбцов.

3. Упрощение доступа к некоторым параметрам и инструментам, расположенным в различных диалоговых окнах программы.

4. Автоматизация сложных последовательностей действий.

Последовательность макросов может быть записана или создана с нуля путем введения кода в редактор Visual Basic на одноименном языке программирования.

Включение макросов

По умолчанию макросы доступны не во всех версиях MS Word, точнее, они просто не включены. Чтобы активировать их необходимо включить средства разработчика. После этого на панели управления программы появится вкладка “Разработчик”. О том, как это сделать, читайте ниже.

Примечание: В версиях программы, в которых макросы доступны изначально (например, Ворд 2016), средства для работы с ними находятся во вкладке “Вид” в группе “Макросы”.

Кнопка Макросы в Word

1. Откройте меню “Файл” (кнопка “Microsoft Office” ранее).

2. Выберите пункт “Параметры” (ранее “Параметры Word”).

3. Откройте в окне “Параметры” категорию “Основные” и перейдите в группе “Основные параметры работы”.

4. Установите галочку напротив пункта “Показывать вкладку “Разработчик” на ленте”.

5. На панели управления появится вкладка “Разработчик”, в которой и будет находиться пункт “Макросы”.

Запись макросов

1. Во вкладке “Разработчик” или, в зависимости от используемой версии Ворда, во вкладке “Вид”, нажмите кнопку “Макросы” и выберите пункт “Запись макроса”.

Запись макроса в Word

2. Задайте имя для создаваемого макроса.

Окно Запись макроса в word

Примечание: Если вы, создавая новый макрос, даете ему точно такое же имя, как у встроенного в программу, действия, записанные вами в новый макрос, будут выполняться взамен стандартным. Для просмотра макросов, доступных в MS Word по умолчанию, в меню кнопки “Макросы” выберите “Команды Word”.

3. В пункте “Макрос доступен для” выберите то, для чего он будет доступен: шаблон или документ, в который его следует сохранить.

Выбор места для применения макроса в Word

    Совет: Если вы хотите, чтобы создаваемый макрос был доступен во всех документах, с которыми вы работаете в дальнейшем, выберите параметр “Normal.dotm”.

4. В поле “Описание” введите описание для создаваемого макроса.

Описание макроса в Word

5. Выполните одно из действий, указанных ниже:

  • Начните запись — чтобы приступить к началу записи макроса, не связывая его при этом с кнопкой на панели управления или комбинацией клавиш, нажмите “ОК”.
  • Создайте кнопку — чтобы связать создаваемый макрос с кнопкой, расположенной на панели управления, выполните следующее:
      • Нажмите “кнопке”;
          • Выберите документ или документы, в которых требуется добавить создаваемый макрос на панель быстрого доступа (раздел “Настройка панели быстрого доступа”);

          Параметры макроса в Word

            Совет: Чтобы создаваемый макрос был доступен для всех документов, выберите параметр “Normal.dotm”.

          Доступ к макросу в Word

          В окне “Макрос из” (ранее “Выбрать команды из”) выберите макрос, который следует записать, нажмите “Добавить”.

          Добавить макрос в Word

            • Если вы хотите настроить эту кнопку, нажмите “Изменить”;
              • Выберите подходящий символ для создаваемой кнопки в поле “Символ”;
                • Введите имя макроса, которое будет отображаться в дальнейшем в поле “Отображаемое имя”;
                  • Для начала записи макроса дважды кликните по кнопке “ОК”.

                  Запись макроса ОК в Word

                  Символ, который вы выбрали, будет отображаться на панели быстрого доступа. При наведении указателя курсора на этот символ, будет отображаться его имя.

                1. Назначьте сочетание клавиш — Для того, чтобы назначить комбинацию клавиш для создаваемого макроса, выполните следующие действия:
                    • Кликните по кнопке “Клавишами” (ранее “Клавиатура”);
                    • Запись макроса клавишами в Word

                        • В разделе “Команды” выберите макрос, который необходимо записать;

                        Настройка клавиатуры в Word

                          • В разделе “Новое сочетание клавиш” введите любую удобную для вас комбинацию, после чего нажмите кнопку “Назначить”;

                          Настройка комбинаций клавиатуры в Word

                            • Для начала записи макроса нажмите “Закрыть”.

                            6. Выполните поочередно все те действия, которые необходимо включить в макрос.

                            Примечание: Во время записи макроса нельзя использовать мышь для выделения текста, а вот для выбора команд и параметров нужно использовать именно ее. При необходимости, выделить текст можно с помощью клавиатуры.

                            7. Для остановки записи макроса нажмите “Остановить запись”, эта команда расположена в меню кнопки “Макросы” на панели управления.

                            остановить запись макроса в Word

                            Изменение комбинаций клавиш для макроса

                            1. Откройте окно “Параметры” (меню “Файл” или кнопка “MS Office”).

                            2. Выберите пункт “Настройка”.

                            3. Нажмите на кнопку “Настройка”, расположенную рядом с полем “Сочетание клавиш”.

                            4. В разделе “Категории” выберите “Макросы”.

                            5. В открывшемся списке выберите макрос, который необходимо изменить.

                            6. Кликните по полю “Новое сочетание клавиш” и нажмите клавиши или комбинацию клавиш, которые вы хотите назначить для конкретного макроса.

                            Настройка клавиатуры в Word

                            7. Убедитесь, что назначенное вами сочетание клавиш не используется для выполнения другой задачи (поле “Текущее сочетание”).

                            8. В разделе “Сохранить изменения” выберите подходящий вариант (место) для сохранения места, где макрос будет запускаться.

                            Сохранить Настройки клавиатуры в word

                              Совет: Если вы хотите, чтобы макрос был доступен к использованию во всех документах, выберите параметр “Normal.dotm”.

                            9. Нажмите “Закрыть”.

                            Запуск макроса

                            1. Нажмите на кнопку “Макросы” (вкладка “Вид” или “Разработчик”, в зависимости от используемой версии программы).

                            Открыть макросы в Word

                            2. Выберите макрос, который хотите запустить (список “Имя макроса”).

                            3. Нажмите “Выполнить”.

                            Выбор Макроса в Word

                            Создание нового макроса

                            1. Нажмите кнопку “Макросы”.

                            Кнопка макросы в Word

                            2. Задайте имя для нового макроса в соответствующем поле.

                            Имя Макроса в Word

                            3. В разделе “Макросы из” выберите шаблон или документ, для которого будет сохранен создаваемый макрос.

                            Создать Макрос в Word

                              Совет: Если вы хотите, чтобы макрос стал доступен во всех документах, выберите параметр “Normal.dotm”.

                            4. Нажмите “Создать”. Будет открыт редактор Visual Basic, в котором и можно будет создать новый макрос на языке Visual Basic.

                            Microsoft Visual Basic for Applications - Normal

                            На этом все, теперь вы знаете, что такое макросы в MS Word, зачем они нужны, как их создавать и как с ними работать. Надеемся, информация из этой статьи будет полезной для вас и действительно поможет упростить, ускорить работу со столь продвинутой офисной программой.

                            Мы рады, что смогли помочь Вам в решении проблемы.

                            Помимо этой статьи, на сайте еще 11902 инструкций.
                            Добавьте сайт Lumpics.ru в закладки (CTRL+D) и мы точно еще пригодимся вам.

                            Отблагодарите автора, поделитесь статьей в социальных сетях.

                            Опишите, что у вас не получилось. Наши специалисты постараются ответить максимально быстро.

                            Как написать скрипт в ворде

                            Помогите пожалуйста со скриптом/макросом для MS Word.
                            Есть часто приходящие списки клиентов, которые необходимо пере-форматировать для удобочитаемости:
                            Формат исходных списков: пример:

                            1Иванов/Кирилл какой-то комментарий
                            .продолжение комментария
                            1Петров/Иван снова какой-то комментарий
                            .снова продолжение коментария
                            .может быть длинный коментарий
                            1Сидоров/Максим опять комментарий
                            .и тут тоже продолжение..

                            на выходе после обработке такого списка хотелось бы получить:

                            1Иванов/Кирилл какой-то комментарий .продолжение комментария
                            1Петров/Иван снова какой-то комментарий .снова продолжение коментария .может быть длинный коментарий
                            1Сидоров/Максим опять комментарий .и тут тоже продолжение..

                            то есть, скрипт должен: проверять если первый символ в строчке 1 — ничего не делать,
                            на следующей строчке если первый символ . — то стирать «перенос строки» и «лепить» к предыдущей строке.

                            В скриптах не понимаю ничего. =)

                            Заранее спасибо за помощь,
                            С уважением,
                            Виктор Бу.

                            title description ms.date ms.prod ms.localizationpriority

                            Word add-in tutorial

                            In this tutorial, you’ll build a Word add-in that inserts (and replaces) text ranges, paragraphs, images, HTML, tables, and content controls. You’ll also learn how to format text and how to insert (and replace) content in content controls.

                            03/14/2023

                            word

                            high

                            Tutorial: Create a Word task pane add-in

                            In this tutorial, you’ll create a Word task pane add-in that:

                            [!div class=»checklist»]

                            • Inserts a range of text
                            • Formats text
                            • Replaces text and inserts text in various locations
                            • Inserts images, HTML, and tables
                            • Creates and updates content controls

                            [!TIP]
                            If you’ve already completed the Build your first Word task pane add-in quick start, and want to use that project as a starting point for this tutorial, go directly to the Insert a range of text section to start this tutorial.

                            Prerequisites

                            [!includeYeoman generator prerequisites]

                            • Office connected to a Microsoft 365 subscription (including Office on the web).

                              [!NOTE]
                              If you don’t already have Office, you can join the Microsoft 365 developer program to get a free, 90-day renewable Microsoft 365 subscription to use during development.

                            Create your add-in project

                            [!includeYeoman generator create project guidance]

                            • Choose a project type: Office Add-in Task Pane project
                            • Choose a script type: JavaScript
                            • What do you want to name your add-in? My Office Add-in
                            • Which Office client application would you like to support? Word

                            Screenshot showing the prompts and answers for the Yeoman generator in a command line interface.

                            After you complete the wizard, the generator creates the project and installs supporting Node components.

                            [!includeYeoman generator next steps]

                            Insert a range of text

                            In this step of the tutorial, you’ll programmatically test that your add-in supports the user’s current version of Word, and then insert a paragraph into the document.

                            Code the add-in

                            1. Open the project in your code editor.

                            2. Open the file ./src/taskpane/taskpane.html. This file contains the HTML markup for the task pane.

                            3. Locate the <main> element and delete all lines that appear after the opening <main> tag and before the closing </main> tag.

                            4. Add the following markup immediately after the opening <main> tag.

                              <button class="ms-Button" id="insert-paragraph">Insert Paragraph</button><br/><br/>
                            5. Open the file ./src/taskpane/taskpane.js. This file contains the Office JavaScript API code that facilitates interaction between the task pane and the Office client application.

                            6. Remove all references to the run button and the run() function by doing the following:

                              • Locate and delete the line document.getElementById("run").onclick = run;.

                              • Locate and delete the entire run() function.

                            7. Within the Office.onReady function call, locate the line if (info.host === Office.HostType.Word) { and add the following code immediately after that line. Note:

                              • This code adds an event handler for the insert-paragraph button.
                              • The insertParagraph function is wrapped in a call to tryCatch (both functions will be added in the next step). This allows any errors generated by the Office JavaScript API layer to be handled separately from your service code.
                              // Assign event handlers and other initialization logic.
                              document.getElementById("insert-paragraph").onclick = () => tryCatch(insertParagraph);
                            8. Add the following functions to the end of the file. Note:

                              • Your Word.js business logic will be added to the function passed to Word.run. This logic doesn’t execute immediately. Instead, it’s added to a queue of pending commands.

                              • The context.sync method sends all queued commands to Word for execution.

                              • The tryCatch function will be used by all the functions interacting with the workbook from the task pane. Catching Office JavaScript errors in this fashion is a convenient way to generically handle uncaught errors.

                              async function insertParagraph() {
                                  await Word.run(async (context) => {
                              
                                      // TODO1: Queue commands to insert a paragraph into the document.
                              
                                      await context.sync();
                                  });
                              }
                              
                              /** Default helper for invoking an action and handling errors. */
                              async function tryCatch(callback) {
                                  try {
                                      await callback();
                                  } catch (error) {
                                      // Note: In a production add-in, you'd want to notify the user through your add-in's UI.
                                      console.error(error);
                                  }
                              }
                            9. Within the insertParagraph() function, replace TODO1 with the following code. Note:

                              • The first parameter to the insertParagraph method is the text for the new paragraph.

                              • The second parameter is the location within the body where the paragraph will be inserted. Other options for insert paragraph, when the parent object is the body, are «End» and «Replace».

                              const docBody = context.document.body;
                              docBody.insertParagraph("Office has several versions, including Office 2016, Microsoft 365 subscription, and Office on the web.",
                                                      Word.InsertLocation.start);
                            10. Save all your changes to the project.

                            Test the add-in

                            1. Complete the following steps to start the local web server and sideload your add-in.

                              [!INCLUDE alert use https]

                              [!TIP]
                              If you’re testing your add-in on Mac, run the following command in the root directory of your project before proceeding. When you run this command, the local web server starts.

                              • To test your add-in in Word, run the following command in the root directory of your project. This starts the local web server (if it isn’t already running) and opens Word with your add-in loaded.

                              • To test your add-in in Word on the web, run the following command in the root directory of your project. When you run this command, the local web server starts. Replace «{url}» with the URL of a Word document on your OneDrive or a SharePoint library to which you have permissions.

                                [!INCLUDE npm start:web command syntax]

                            2. In Word, if the «My Office Add-in» task pane isn’t already open, choose the Home tab, and then choose the Show Taskpane button in the ribbon to open the add-in task pane.

                              Screenshot displaying the Show Taskpane button highlighted in Word.

                            3. In the task pane, choose the Insert Paragraph button.

                            4. Make a change in the paragraph.

                            5. Choose the Insert Paragraph button again. Note that the new paragraph appears above the previous one because the insertParagraph method is inserting at the start of the document’s body.

                              Screenshot showing the Insert Paragraph button in the add-in.

                            Format text

                            In this step of the tutorial, you’ll apply a built-in style to text, apply a custom style to text, and change the font of text.

                            Apply a built-in style to text

                            1. Open the file ./src/taskpane/taskpane.html.

                            2. Locate the <button> element for the insert-paragraph button, and add the following markup after that line.

                              <button class="ms-Button" id="apply-style">Apply Style</button><br/><br/>
                            3. Open the file ./src/taskpane/taskpane.js.

                            4. Within the Office.onReady function call, locate the line that assigns a click handler to the insert-paragraph button, and add the following code after that line.

                              document.getElementById("apply-style").onclick = () => tryCatch(applyStyle);
                            5. Add the following function to the end of the file.

                              async function applyStyle() {
                                  await Word.run(async (context) => {
                              
                                      // TODO1: Queue commands to style text.
                              
                                      await context.sync();
                                  });
                              }
                            6. Within the applyStyle() function, replace TODO1 with the following code. Note that the code applies a style to a paragraph, but styles can also be applied to ranges of text.

                              const firstParagraph = context.document.body.paragraphs.getFirst();
                              firstParagraph.styleBuiltIn = Word.Style.intenseReference;

                            Apply a custom style to text

                            1. Open the file ./src/taskpane/taskpane.html.

                            2. Locate the <button> element for the apply-style button, and add the following markup after that line.

                              <button class="ms-Button" id="apply-custom-style">Apply Custom Style</button><br/><br/>
                            3. Open the file ./src/taskpane/taskpane.js.

                            4. Within the Office.onReady function call, locate the line that assigns a click handler to the apply-style button, and add the following code after that line.

                              document.getElementById("apply-custom-style").onclick = () => tryCatch(applyCustomStyle);
                            5. Add the following function to the end of the file.

                              async function applyCustomStyle() {
                                  await Word.run(async (context) => {
                              
                                      // TODO1: Queue commands to apply the custom style.
                              
                                      await context.sync();
                                  });
                              }
                            6. Within the applyCustomStyle() function, replace TODO1 with the following code. Note that the code applies a custom style that does not exist yet. You’ll create a style with the name MyCustomStyle in the Test the add-in step.

                              const lastParagraph = context.document.body.paragraphs.getLast();
                              lastParagraph.style = "MyCustomStyle";
                            7. Save all your changes to the project.

                            Change the font of text

                            1. Open the file ./src/taskpane/taskpane.html.

                            2. Locate the <button> element for the apply-custom-style button, and add the following markup after that line.

                              <button class="ms-Button" id="change-font">Change Font</button><br/><br/>
                            3. Open the file ./src/taskpane/taskpane.js.

                            4. Within the Office.onReady function call, locate the line that assigns a click handler to the apply-custom-style button, and add the following code after that line.

                              document.getElementById("change-font").onclick = () => tryCatch(changeFont);
                            5. Add the following function to the end of the file.

                              async function changeFont() {
                                  await Word.run(async (context) => {
                              
                                      // TODO1: Queue commands to apply a different font.
                              
                                      await context.sync();
                                  });
                              }
                            6. Within the changeFont() function, replace TODO1 with the following code. Note that the code gets a reference to the second paragraph by using the ParagraphCollection.getFirst method chained to the Paragraph.getNext method.

                              const secondParagraph = context.document.body.paragraphs.getFirst().getNext();
                              secondParagraph.font.set({
                                      name: "Courier New",
                                      bold: true,
                                      size: 18
                                  });
                            7. Save all your changes to the project.

                            Test the add-in

                            1. [!includeStart server and sideload add-in instructions]

                            2. If the add-in task pane isn’t already open in Word, go to the Home tab and choose the Show Taskpane button in the ribbon to open it.

                            3. Be sure there are at least three paragraphs in the document. You can choose the Insert Paragraph button three times. Check carefully that there’s no blank paragraph at the end of the document. If there is, delete it.

                            4. In Word, create a custom style named «MyCustomStyle». It can have any formatting that you want.

                            5. Choose the Apply Style button. The first paragraph will be styled with the built-in style Intense Reference.

                            6. Choose the Apply Custom Style button. The last paragraph will be styled with your custom style. (If nothing seems to happen, the last paragraph might be blank. If so, add some text to it.)

                            7. Choose the Change Font button. The font of the second paragraph changes to 18 pt., bold, Courier New.

                              Screenshot showing the results of applying the styles and fonts defined for the add-in buttons Apply Style, Apply Custom Style, and Change font.

                            Replace text and insert text

                            In this step of the tutorial, you’ll add text inside and outside of selected ranges of text, and replace the text of a selected range.

                            Add text inside a range

                            1. Open the file ./src/taskpane/taskpane.html.

                            2. Locate the <button> element for the change-font button, and add the following markup after that line.

                              <button class="ms-Button" id="insert-text-into-range">Insert Abbreviation</button><br/><br/>
                            3. Open the file ./src/taskpane/taskpane.js.

                            4. Within the Office.onReady function call, locate the line that assigns a click handler to the change-font button, and add the following code after that line.

                              document.getElementById("insert-text-into-range").onclick = () => tryCatch(insertTextIntoRange);
                            5. Add the following function to the end of the file.

                              async function insertTextIntoRange() {
                                  await Word.run(async (context) => {
                              
                                      // TODO1: Queue commands to insert text into a selected range.
                              
                                      // TODO2: Load the text of the range and sync so that the
                                      //        current range text can be read.
                              
                                      // TODO3: Queue commands to repeat the text of the original
                                      //        range at the end of the document.
                              
                                      await context.sync();
                                  });
                              }
                            6. Within the insertTextIntoRange() function, replace TODO1 with the following code. Note:

                              • The function is intended to insert the abbreviation [«(M365)»] into the end of the Range whose text is «Microsoft 365». It makes a simplifying assumption that the string is present and the user has selected it.

                              • The first parameter of the Range.insertText method is the string to insert into the Range object.

                              • The second parameter specifies where in the range the additional text should be inserted. Besides «End», the other possible options are «Start», «Before», «After», and «Replace».

                              • The difference between «End» and «After» is that «End» inserts the new text inside the end of the existing range, but «After» creates a new range with the string and inserts the new range after the existing range. Similarly, «Start» inserts text inside the beginning of the existing range and «Before» inserts a new range. «Replace» replaces the text of the existing range with the string in the first parameter.

                              • You saw in an earlier stage of the tutorial that the insert* methods of the body object don’t have the «Before» and «After» options. This is because you can’t put content outside of the document’s body.

                              const doc = context.document;
                              const originalRange = doc.getSelection();
                              originalRange.insertText(" (M365)", Word.InsertLocation.end);
                            7. We’ll skip over TODO2 until the next section. Within the insertTextIntoRange() function, replace TODO3 with the following code. This code is similar to the code you created in the first stage of the tutorial, except that now you are inserting a new paragraph at the end of the document instead of at the start. This new paragraph will demonstrate that the new text is now part of the original range.

                              doc.body.insertParagraph("Original range: " + originalRange.text, Word.InsertLocation.end);

                            Add code to fetch document properties into the task pane’s script objects

                            In all previous functions in this tutorial, you queued commands to write to the Office document. Each function ended with a call to the context.sync() method which sends the queued commands to the document to be executed. But the code you added in the last step calls the originalRange.text property, and this is a significant difference from the earlier functions you wrote, because the originalRange object is only a proxy object that exists in your task pane’s script. It doesn’t know what the actual text of the range in the document is, so its text property can’t have a real value. It’s necessary to first fetch the text value of the range from the document and use it to set the value of originalRange.text. Only then can originalRange.text be called without causing an exception to be thrown. This fetching process has three steps.

                            1. Queue a command to load (that is, fetch) the properties that your code needs to read.

                            2. Call the context object’s sync method to send the queued command to the document for execution and return the requested information.

                            3. Because the sync method is asynchronous, ensure that it has completed before your code calls the properties that were fetched.

                            The following step must be completed whenever your code needs to read information from the Office document.

                            1. Within the insertTextIntoRange() function, replace TODO2 with the following code.

                              originalRange.load("text");
                              await context.sync();

                            When you’re done, the entire function should look like the following:

                            async function insertTextIntoRange() {
                                await Word.run(async (context) => {
                            
                                    const doc = context.document;
                                    const originalRange = doc.getSelection();
                                    originalRange.insertText(" (M365)", Word.InsertLocation.end);
                            
                                    originalRange.load("text");
                                    await context.sync();
                            
                                    doc.body.insertParagraph("Original range: " + originalRange.text, Word.InsertLocation.end);
                            
                                    await context.sync();
                                });
                            }

                            Add text between ranges

                            1. Open the file ./src/taskpane/taskpane.html.

                            2. Locate the <button> element for the insert-text-into-range button, and add the following markup after that line.

                              <button class="ms-Button" id="insert-text-outside-range">Add Version Info</button><br/><br/>
                            3. Open the file ./src/taskpane/taskpane.js.

                            4. Within the Office.onReady function call, locate the line that assigns a click handler to the insert-text-into-range button, and add the following code after that line.

                              document.getElementById("insert-text-outside-range").onclick = () => tryCatch(insertTextBeforeRange);
                            5. Add the following function to the end of the file.

                              async function insertTextBeforeRange() {
                                  await Word.run(async (context) => {
                              
                                      // TODO1: Queue commands to insert a new range before the
                                      //        selected range.
                              
                                      // TODO2: Load the text of the original range and sync so that the
                                      //        range text can be read and inserted.
                              
                                  });
                              }
                            6. Within the insertTextBeforeRange() function, replace TODO1 with the following code. Note:

                              • The function is intended to add a range whose text is «Office 2019, » before the range with text «Microsoft 365». It makes an assumption that the string is present and the user has selected it.

                              • The first parameter of the Range.insertText method is the string to add.

                              • The second parameter specifies where in the range the additional text should be inserted. For more details about the location options, see the previous discussion of the insertTextIntoRange function.

                              const doc = context.document;
                              const originalRange = doc.getSelection();
                              originalRange.insertText("Office 2019, ", Word.InsertLocation.before);
                            7. Within the insertTextBeforeRange() function, replace TODO2 with the following code.

                              originalRange.load("text");
                              await context.sync();
                              
                              // TODO3: Queue commands to insert the original range as a
                              //        paragraph at the end of the document.
                              
                              // TODO4: Make a final call of context.sync here and ensure
                              //        that it runs after the insertParagraph has been queued.
                            8. Replace TODO3 with the following code. This new paragraph will demonstrate the fact that the new text is not part of the original selected range. The original range still has only the text it had when it was selected.

                              doc.body.insertParagraph("Current text of original range: " + originalRange.text, Word.InsertLocation.end);
                            9. Replace TODO4 with the following code.

                            Replace the text of a range

                            1. Open the file ./src/taskpane/taskpane.html.

                            2. Locate the <button> element for the insert-text-outside-range button, and add the following markup after that line.

                              <button class="ms-Button" id="replace-text">Change Quantity Term</button><br/><br/>
                            3. Open the file ./src/taskpane/taskpane.js.

                            4. Within the Office.onReady function call, locate the line that assigns a click handler to the insert-text-outside-range button, and add the following code after that line.

                              document.getElementById("replace-text").onclick = () => tryCatch(replaceText);
                            5. Add the following function to the end of the file.

                              async function replaceText() {
                                  await Word.run(async (context) => {
                              
                                      // TODO1: Queue commands to replace the text.
                              
                                      await context.sync();
                                  });
                              }
                            6. Within the replaceText() function, replace TODO1 with the following code. Note that the function is intended to replace the string «several» with the string «many». It makes a simplifying assumption that the string is present and the user has selected it.

                              const doc = context.document;
                              const originalRange = doc.getSelection();
                              originalRange.insertText("many", Word.InsertLocation.replace);
                            7. Save all your changes to the project.

                            Test the add-in

                            1. [!includeStart server and sideload add-in instructions]

                            2. If the add-in task pane isn’t already open in Word, go to the Home tab and choose the Show Taskpane button in the ribbon to open it.

                            3. In the task pane, choose the Insert Paragraph button to ensure that there’s a paragraph at the start of the document.

                            4. Within the document, select the phrase «Microsoft 365 subscription». Be careful not to include the preceding space or following comma in the selection.

                            5. Choose the Insert Abbreviation button. Note that » (M365)» is added. Note also that at the bottom of the document a new paragraph is added with the entire expanded text because the new string was added to the existing range.

                            6. Within the document, select the phrase «Microsoft 365». Be careful not to include the preceding or following space in the selection.

                            7. Choose the Add Version Info button. Note that «Office 2019, » is inserted between «Office 2016» and «Microsoft 365». Note also that at the bottom of the document a new paragraph is added but it contains only the originally selected text because the new string became a new range rather than being added to the original range.

                            8. Within the document, select the word «several». Be careful not to include the preceding or following space in the selection.

                            9. Choose the Change Quantity Term button. Note that «many» replaces the selected text.

                              Screenshot showing the results of choosing the add-in buttons Insert Abbreviation, Add Version Info, and Change Quantity Term.

                            Insert images, HTML, and tables

                            In this step of the tutorial, you’ll learn how to insert images, HTML, and tables into the document.

                            Define an image

                            Complete the following steps to define the image that you’ll insert into the document in the next part of this tutorial.

                            1. In the root of the project, create a new file named base64Image.js.

                            2. Open the file base64Image.js and add the following code to specify the Base64-encoded string that represents an image.

                              export const base64Image =
                                  "iVBORw0KGgoAAAANSUhEUgAAAZAAAAEFCAIAAABCdiZrAAAACXBIWXMAAAsSAAALEgHS3X78AAAgAElEQVR42u2dzW9bV3rGn0w5wLBTRpSACAUDmDRowGoj1DdAtBA6suksZmtmV3Qj+i8w3XUB00X3pv8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sv+qHoUgoFzmLzSfYqjOyQMEiQZAysFXHJ19OMWaZuCpjV3D9EXbYv5iCRQJnrYBti9uIgUmVvYzBIcUAAAIqSURBVAmYLfNiULBIaGRK2GlyG9HfNdzFtsVNQAoWiYrBNiJlayq4CUjBIjMyNWnkK9i2uI3oVqq4CUjBIjPG3kbcec1tRPUlysL4nJuAFCwSJ9mytxEpWyNF6Ao2n2CnqZyXQShYZGasFbBV5zZiX6rsTUDmFShYJNbY24jXHy3venxmt39omZuAFCwyH2TLy7iNuH6nvwlIqaJgkXmzRcu0jWhvAho1bgJSsMg8M9hGXL+zoD9gtp9X4CYgBYssjmwZtUXbRrQPLe80KVUULLKI2NuIxudzv41obwJuW9wEpGCRRWe92O/FPKfr8VfucROQgkWWjExp/rYR7c7FG1VKFQWLLB+DXszx30a0NwF5aJlQsChb/W3EeMpW6gY3AQkFi4xipx9itY1obwJuW5QqIj5keQkIEJuRrhxfSlhhkSlka4YjXTm+lFCwyNREP9KV40sJBYv4sGY/bCNeuRfuC63ewvYrbgISChYJQrY2qmFtIw46F6cMXmlCwSIBEfhIV44vJRQsEi6BjHTl+FJCwSLR4XmkK8eXEgoWmQ3TjnTl+FJCwSIzZjDSVQPHl5JAee/du3e8CsQX3Sa6Y730pB8khIJFCKElJIQQChYhhFCwCCEULEIIoWARQggFixBCwSKEEAoWIYRQsAghFCxCCKFgEUIIBYsQQsEihBAKFiGEULAIIRQsQgihYBFCCAWLEELBIoQQChYhhILFS0AIoWARQkjA/D87uqZQTj7xTgAAAABJRU5ErkJggg==";

                            Insert an image

                            1. Open the file ./src/taskpane/taskpane.html.

                            2. Locate the <button> element for the replace-text button, and add the following markup after that line.

                              <button class="ms-Button" id="insert-image">Insert Image</button><br/><br/>
                            3. Open the file ./src/taskpane/taskpane.js.

                            4. Locate the Office.onReady function call near the top of the file and add the following code immediately before that line. This code imports the variable that you defined previously in the file ./base64Image.js.

                              import { base64Image } from "../../base64Image";
                            5. Within the Office.onReady function call, locate the line that assigns a click handler to the replace-text button, and add the following code after that line.

                              document.getElementById("insert-image").onclick = () => tryCatch(insertImage);
                            6. Add the following function to the end of the file.

                              async function insertImage() {
                                  await Word.run(async (context) => {
                              
                                      // TODO1: Queue commands to insert an image.
                              
                                      await context.sync();
                                  });
                              }
                            7. Within the insertImage() function, replace TODO1 with the following code. Note that this line inserts the Base64-encoded image at the end of the document. (The Paragraph object also has an insertInlinePictureFromBase64 method and other insert* methods. See the following «Insert HTML» section for an example.)

                              context.document.body.insertInlinePictureFromBase64(base64Image, Word.InsertLocation.end);

                            Insert HTML

                            1. Open the file ./src/taskpane/taskpane.html.

                            2. Locate the <button> element for the insert-image button, and add the following markup after that line.

                              <button class="ms-Button" id="insert-html">Insert HTML</button><br/><br/>
                            3. Open the file ./src/taskpane/taskpane.js.

                            4. Within the Office.onReady function call, locate the line that assigns a click handler to the insert-image button, and add the following code after that line.

                              document.getElementById("insert-html").onclick = () => tryCatch(insertHTML);
                            5. Add the following function to the end of the file.

                              async function insertHTML() {
                                  await Word.run(async (context) => {
                              
                                      // TODO1: Queue commands to insert a string of HTML.
                              
                                      await context.sync();
                                  });
                              }
                            6. Within the insertHTML() function, replace TODO1 with the following code. Note:

                              • The first line adds a blank paragraph to the end of the document.

                              • The second line inserts a string of HTML at the end of the paragraph; specifically two paragraphs, one formatted with the Verdana font, the other with the default styling of the Word document. (As you saw in the insertImage method earlier, the context.document.body object also has the insert* methods.)

                              const blankParagraph = context.document.body.paragraphs.getLast().insertParagraph("", Word.InsertLocation.after);
                              blankParagraph.insertHtml('<p style="font-family: verdana;">Inserted HTML.</p><p>Another paragraph</p>', Word.InsertLocation.end);

                            Insert a table

                            1. Open the file ./src/taskpane/taskpane.html.

                            2. Locate the <button> element for the insert-html button, and add the following markup after that line.

                              <button class="ms-Button" id="insert-table">Insert Table</button><br/><br/>
                            3. Open the file ./src/taskpane/taskpane.js.

                            4. Within the Office.onReady function call, locate the line that assigns a click handler to the insert-html button, and add the following code after that line.

                              document.getElementById("insert-table").onclick = () => tryCatch(insertTable);
                            5. Add the following function to the end of the file.

                              async function insertTable() {
                                  await Word.run(async (context) => {
                              
                                      // TODO1: Queue commands to get a reference to the paragraph
                                      //        that will precede the table.
                              
                                      // TODO2: Queue commands to create a table and populate it with data.
                              
                                      await context.sync();
                                  });
                              }
                            6. Within the insertTable() function, replace TODO1 with the following code. Note that this line uses the ParagraphCollection.getFirst method to get a reference to the first paragraph and then uses the Paragraph.getNext method to get a reference to the second paragraph.

                              const secondParagraph = context.document.body.paragraphs.getFirst().getNext();
                            7. Within the insertTable() function, replace TODO2 with the following code. Note:

                              • The first two parameters of the insertTable method specify the number of rows and columns.

                              • The third parameter specifies where to insert the table, in this case after the paragraph.

                              • The fourth parameter is a two-dimensional array that sets the values of the table cells.

                              • The table will have plain default styling, but the insertTable method returns a Table object with many members, some of which are used to style the table.

                              const tableData = [
                                      ["Name", "ID", "Birth City"],
                                      ["Bob", "434", "Chicago"],
                                      ["Sue", "719", "Havana"],
                                  ];
                              secondParagraph.insertTable(3, 3, Word.InsertLocation.after, tableData);
                            8. Save all your changes to the project.

                            Test the add-in

                            1. [!includeStart server and sideload add-in instructions]

                            2. If the add-in task pane isn’t already open in Word, go to the Home tab and choose the Show Taskpane button in the ribbon to open it.

                            3. In the task pane, choose the Insert Paragraph button at least three times to ensure that there are a few paragraphs in the document.

                            4. Choose the Insert Image button and note that an image is inserted at the end of the document.

                            5. Choose the Insert HTML button and note that two paragraphs are inserted at the end of the document, and that the first one has the Verdana font.

                            6. Choose the Insert Table button and note that a table is inserted after the second paragraph.

                              Screenshot showing the results of choosing the add-in buttons Insert Image, Insert HTML, and Insert Table.

                            Create and update content controls

                            In this step of the tutorial, you’ll learn how to create Rich Text content controls in the document, and then how to insert and replace content in the controls.

                            [!NOTE]
                            There are several types of content controls that can be added to a Word document through the UI, but currently only Rich Text content controls are supported by Word.js.

                            Before you start this step of the tutorial, we recommend that you create and manipulate Rich Text content controls through the Word UI, so you can be familiar with the controls and their properties. For details, see Create forms that users complete or print in Word.

                            Create a content control

                            1. Open the file ./src/taskpane/taskpane.html.

                            2. Locate the <button> element for the insert-table button, and add the following markup after that line.

                              <button class="ms-Button" id="create-content-control">Create Content Control</button><br/><br/>
                            3. Open the file ./src/taskpane/taskpane.js.

                            4. Within the Office.onReady function call, locate the line that assigns a click handler to the insert-table button, and add the following code after that line.

                              document.getElementById("create-content-control").onclick = () => tryCatch(createContentControl);
                            5. Add the following function to the end of the file.

                              async function createContentControl() {
                                  await Word.run(async (context) => {
                              
                                      // TODO1: Queue commands to create a content control.
                              
                                      await context.sync();
                                  });
                              }
                            6. Within the createContentControl() function, replace TODO1 with the following code. Note:

                              • This code is intended to wrap the phrase «Microsoft 365» in a content control. It makes a simplifying assumption that the string is present and the user has selected it.

                              • The ContentControl.title property specifies the visible title of the content control.

                              • The ContentControl.tag property specifies an tag that can be used to get a reference to a content control using the ContentControlCollection.getByTag method, which you’ll use in a later function.

                              • The ContentControl.appearance property specifies the visual look of the control. Using the value «Tags» means that the control will be wrapped in opening and closing tags, and the opening tag will have the content control’s title. Other possible values are «BoundingBox» and «None».

                              • The ContentControl.color property specifies the color of the tags or the border of the bounding box.

                              const serviceNameRange = context.document.getSelection();
                              const serviceNameContentControl = serviceNameRange.insertContentControl();
                              serviceNameContentControl.title = "Service Name";
                              serviceNameContentControl.tag = "serviceName";
                              serviceNameContentControl.appearance = "Tags";
                              serviceNameContentControl.color = "blue";

                            Replace the content of the content control

                            1. Open the file ./src/taskpane/taskpane.html.

                            2. Locate the <button> element for the create-content-control button, and add the following markup after that line.

                              <button class="ms-Button" id="replace-content-in-control">Rename Service</button><br/><br/>
                            3. Open the file ./src/taskpane/taskpane.js.

                            4. Within the Office.onReady function call, locate the line that assigns a click handler to the create-content-control button, and add the following code after that line.

                              document.getElementById("replace-content-in-control").onclick = () => tryCatch(replaceContentInControl);
                            5. Add the following function to the end of the file.

                              async function replaceContentInControl() {
                                  await Word.run(async (context) => {
                              
                                      // TODO1: Queue commands to replace the text in the Service Name
                                      //        content control.
                              
                                      await context.sync();
                                  });
                              }
                            6. Within the replaceContentInControl() function, replace TODO1 with the following code. Note:

                              • The ContentControlCollection.getByTag method returns a ContentControlCollection of all content controls of the specified tag. We use getFirst to get a reference to the desired control.
                              const serviceNameContentControl = context.document.contentControls.getByTag("serviceName").getFirst();
                              serviceNameContentControl.insertText("Fabrikam Online Productivity Suite", Word.InsertLocation.replace);
                            7. Save all your changes to the project.

                            Test the add-in

                            1. [!includeStart server and sideload add-in instructions]

                            2. If the add-in task pane isn’t already open in Word, go to the Home tab and choose the Show Taskpane button in the ribbon to open it.

                            3. In the task pane, choose the Insert Paragraph button to ensure that there’s a paragraph with «Microsoft 365» at the top of the document.

                            4. In the document, select the text «Microsoft 365» and then choose the Create Content Control button. Note that the phrase is wrapped in tags labelled «Service Name».

                            5. Choose the Rename Service button and note that the text of the content control changes to «Fabrikam Online Productivity Suite».

                              Screenshot showing the results of choosing the add-in buttons Create Content Control and Rename Service.

                            Next steps

                            In this tutorial, you’ve created a Word task pane add-in that inserts and replaces text, images, and other content in a Word document. To learn more about building Word add-ins, continue to the following article.

                            [!div class=»nextstepaction»]
                            Word add-ins overview

                            See also

                            • Office Add-ins platform overview
                            • Develop Office Add-ins

                            Никому не нужно вкладывать небольшое состояние в компьютерные программы, чтобы написать сценарий, когда у них уже есть лучший вариант: Microsoft Word! Есть несколько способов создать профессиональный сценарий с помощью Word. Вы можете использовать макросы (небольшие программы, которые записывают нажатия клавиш и автоматизируют более повторяющиеся задачи для пользователя) или настраивать параметры стиля и форматирования, чтобы сразу же начать думать о сюжетах для телевидения, фильмов или театра.

                            шаги

                            Метод 1 из 5: создание сценария из шаблона

                            Написание сценариев с помощью Microsoft Word Шаг 1

                            Написание сценариев с помощью Microsoft Word Шаг 1

                            Шаг 1. Откройте новый документ

                            Открыв Word, нажмите «Файл» в строке меню в верхнем левом углу экрана, а затем «Создать». Затем у вас будет несколько вариантов стиля и макета для документа.

                            Написание сценариев с помощью Microsoft Word Шаг 2

                            Написание сценариев с помощью Microsoft Word Шаг 2

                            Шаг 2. Найдите шаблон сценария

                            Введите «дорожная карта» в строку поиска. Microsoft предлагает готовый шаблон сценария для версий Word 2013 и 2016 годов. Дважды щелкните по нему после выполнения поиска, чтобы открыть.

                            Шаги в Word 2010 почти такие же: откройте новый документ, выберите шаблоны и выполните поиск в Microsoft Word Online. Затем выберите один из двух вариантов загрузки

                            Написание сценариев с помощью Microsoft Word Шаг 3

                            Написание сценариев с помощью Microsoft Word Шаг 3

                            Шаг 3. Внесите необходимые изменения в шаблон скрипта

                            Когда дело доходит до написания сценария, нет никаких конкретных правил, хотя есть более общие рекомендации относительно стиля, словарного запаса и других характеристик. Обратитесь в студию, для которой вы пишете, чтобы узнать, есть ли чему следовать, и подумайте о таких деталях, как поля, размер и стиль шрифта, а также межстрочный интервал.

                            Написание сценариев с помощью Microsoft Word Шаг 4

                            Написание сценариев с помощью Microsoft Word Шаг 4

                            Шаг 4. Создайте свой собственный шаблон

                            Если вы уже написали сценарий или сохранили файл на жестком диске, откройте его в Word. В версиях программы 2013 и 2016 годов нажмите «Файл», «Сохранить как» и «Этот компьютер». Введите имя файла и в раскрывающемся меню «Тип» нажмите «Шаблон Word». Если документ содержит макросы, щелкните «Шаблон Word с поддержкой макросов». Наконец, нажмите «Сохранить».

                            Если вы хотите изменить место сохранения шаблонов, нажмите «Файл», «Параметры» и «Сохранить» и выберите папку, в которой будут храниться все пользовательские шаблоны

                            Метод 2 из 5. Использование стиля и параметров форматирования

                            Написание сценариев с помощью Microsoft Word Шаг 5

                            Написание сценариев с помощью Microsoft Word Шаг 5

                            Шаг 1. Используйте параметры стиля и форматирования для форматирования сценария

                            Если вам не нравятся шаблоны, предлагаемые Word, вы можете изменить стиль и форматирование документа, чтобы создать что-то более индивидуальное. Затем просто сохраните файл, чтобы использовать его в будущем для других документов этого типа. Выбирайте, как будет выглядеть макет в процессе работы.

                            Написание сценариев с помощью Microsoft Word Шаг 6

                            Написание сценариев с помощью Microsoft Word Шаг 6

                            Шаг 2. Выделите строку текста

                            Эта строка может содержать имя персонажа, часть диалога или инструкции сцены. Щелкните левой кнопкой мыши в левом углу линии, чтобы выбрать ее.

                            • Вы также можете щелкнуть левой кнопкой мыши справа или слева от строки текста, которую хотите настроить, чтобы выделить все.
                            • Наконец, вы также можете поместить курсор над текстом и нажать клавишу Shift и стрелку направления, чтобы выделить текст. Используйте стрелку влево, чтобы выбрать, что идет до, и стрелку вправо, чтобы выбрать, что будет после.
                            • Если строк несколько, выберите каждую отдельно и примените настройки форматирования.

                            Написание сценариев с помощью Microsoft Word Шаг 7

                            Написание сценариев с помощью Microsoft Word Шаг 7

                            Шаг 3. Откройте панель «Стиль и форматирование»

                            Выделив текст, нажмите «Форматировать» в строке меню, чтобы открыть раскрывающееся меню с параметрами. Щелкните «Стили и форматирование», чтобы открыть панель управления.

                            Вы также можете нажать кнопку «Стили и форматирование» на панели инструментов, чтобы открыть панель управления. Он расположен в левом углу страницы, рядом с раскрывающимся меню символов сценария, и представлен двумя перекрывающимися буквами «A» разного цвета

                            Написание сценариев с помощью Microsoft Word Шаг 8

                            Написание сценариев с помощью Microsoft Word Шаг 8

                            Шаг 4. Выделите части текста с похожим форматированием

                            Щелкните правой кнопкой мыши ранее выделенный текст, чтобы открыть раскрывающееся меню с различными параметрами. Последний — «Выбрать текст с похожим форматированием». Щелкните левой кнопкой мыши по нему, чтобы также выделить все похожие части скрипта.

                            Например, если все имена символов написаны одним шрифтом и одного размера и расположены по центру страницы, вы можете выбрать только один из них и использовать параметр «Выбрать текст с аналогичным форматированием», чтобы настроить все сразу

                            Написание сценариев с помощью Microsoft Word Шаг 9

                            Написание сценариев с помощью Microsoft Word Шаг 9

                            Шаг 5. Выберите нужный формат

                            После выбора текста и настройки стиля выберите формат на панели «Стили и форматирование» справа. Когда решите, щелкните левой кнопкой мыши.

                            Написание сценариев с помощью Microsoft Word Шаг 10

                            Написание сценариев с помощью Microsoft Word Шаг 10

                            Шаг 6. Создайте новый стиль

                            Если выделенный текст не соответствует существующему стилю, нажмите кнопку «Новый стиль», которая находится в верхней части панели. Затем придумайте имя, выровняйте текст по правому или левому краю, выберите шрифт и внесите другие изменения.

                            Метод 3 из 5. Создание макроса для сцен сценария (в Word 2013 и 2016)

                            Написание сценариев с помощью Microsoft Word Шаг 11

                            Написание сценариев с помощью Microsoft Word Шаг 11

                            Шаг 1. Поймите, почему вы должны описывать сцены

                            У большинства скриптов есть главный заголовок — серия слов, определяющих содержание, которое следует за ним. Например: заголовок может читать «INT. ОФИС — ДЕНЬ »(внутри офиса, днем), чтобы направить читателя сценария по отношению к сцене.

                            Заголовки сцены должны быть написаны заглавными буквами и располагаться на две строки ниже последней строки диалога или описания предыдущей сцены

                            Написание сценариев с помощью Microsoft Word Шаг 12

                            Написание сценариев с помощью Microsoft Word Шаг 12

                            Шаг 2. Подготовьтесь к записи макроса

                            Макросы — это последовательности сохраненных команд, которые можно выполнить одним нажатием клавиши. Отрегулируйте поля, чтобы подготовить процесс. Для этого откройте вкладку «Макет» и нажмите «Поля» и «Пользовательские поля». Верхнее, нижнее и правое поля должны составлять 1 см, а левое — 1,5 см. Используйте шрифт Courier New, размер 12. Эти параметры являются наиболее распространенными в скриптах, но вы также можете настроить все под себя.

                            В Word 2007 отрегулируйте поля, чтобы подготовиться к записи макроса. Щелкните вкладку «Макет страницы» и поместите поля и шрифт в соответствии с требованиями, перечисленными выше. Затем перейдите на вкладку «Разработчик». Чтобы отобразить его, нажмите кнопку в верхнем левом углу экрана Word и войдите в меню параметров (в конце списка); в «Популярном» установите флажок «Показать разработчика»

                            Написание сценариев с помощью Microsoft Word Шаг 13

                            Написание сценариев с помощью Microsoft Word Шаг 13

                            Шаг 3. Щелкните «Просмотр», «Макросы» и «Запись макроса»

                            Введите имя. Поскольку вы собираетесь использовать макрос для организации сцен, используйте что-то вроде «Заголовок сцены». Наконец, выберите «Все документы» в раскрывающемся списке «Сохранить макрос в».

                            В Word 2007 нажмите «Записать макрос» в левой части вкладки «Разработчик». Сохраните его в «Документе 1» (а не в «Все документы», чтобы вы могли сохранить файл как определенный шаблон сценария). Используйте имя «Сцена» или «Заголовок» и щелкните значок клавиатуры, чтобы создать ярлык. Затем нажмите кнопки быстрого доступа. Например: если вы хотите использовать F2, нажмите клавишу с курсором в поле «Press New Shortcut Key». Наконец, нажмите «Назначить» и «Закрыть»

                            Написание сценариев с помощью Microsoft Word Шаг 14

                            Написание сценариев с помощью Microsoft Word Шаг 14

                            Шаг 4. Щелкните значок клавиатуры

                            Затем назначьте макрос клавише F2 (или любой другой по вашему выбору) в поле «Нажмите новую комбинацию клавиш». Нажмите «Назначить» и нажмите Enter или нажмите «Закрыть».

                            Написание сценариев с помощью Microsoft Word Шаг 15

                            Написание сценариев с помощью Microsoft Word Шаг 15

                            Шаг 5. Найдите значок диктофона рядом с мышью

                            Дважды нажмите Enter на клавиатуре, чтобы пропустить строки. Вернитесь на вкладку «Макет» («Макет страницы» в Word 2007) и сбросьте оба отступа до нуля. Откройте вкладку «Главная» и щелкните в правом нижнем углу раздела «Источник», чтобы открыть диалоговое окно. Наконец, в разделе «Эффекты» установите флажок «Все заглавными буквами» и нажмите «ОК».

                            Написание сценариев с помощью Microsoft Word Шаг 16

                            Написание сценариев с помощью Microsoft Word Шаг 16

                            Шаг 6. Завершите макрос

                            Щелкните вкладку «Предварительный просмотр» еще раз. Затем нажмите «Макросы» и «Остановить запись». С этого момента клавиша F2 всегда будет пропускать две строки на странице и вводить текст с заглавной буквы, чтобы вы могли ввести заголовок.

                            В Word 2007 перейдите на вкладку «Разработчик» и нажмите «Остановить запись». С этого момента клавиша F2 всегда пропускает две строки на странице и делает текст заглавными

                            Метод 4 из 5. Создание макроса для описания (в Word 2013 и 2016)

                            Написание сценариев в Microsoft Word. Шаг 17

                            Написание сценариев в Microsoft Word. Шаг 17

                            Шаг 1. Определите, почему вы хотите создать макрос для описания

                            Описания сценария предоставляют больше деталей, чем заголовок, например, тип освещения, погоду и описания места, где происходит сцена, и задействованных персонажей. Описание находится на две строки под заголовком, первая буква — заглавная, а точка -. Например: под заголовком «INT. ОФИС — ДЕНЬ »можно привести описание« Окно открыто, свет мигает ».

                            Написание сценариев с помощью Microsoft Word Шаг 18

                            Написание сценариев с помощью Microsoft Word Шаг 18

                            Шаг 2. Откройте вкладку «Макет» («Макет страницы» в Word 2007) и настройте поля

                            Щелкните значок в правом нижнем углу раздела «Абзац», чтобы открыть диалоговое окно. Разместите отступы 1 см перед текстом и 1,5 см после в разделе «Отступ».

                            В Word 2007 перейдите на вкладку «Разработчик». Нажмите кнопку в верхнем левом углу экрана Word и войдите в меню параметров (в конце списка); в «Популярном» установите флажок «Показать разработчика»

                            Написание сценариев с помощью Microsoft Word Шаг 19

                            Написание сценариев с помощью Microsoft Word Шаг 19

                            Шаг 3. Щелкните «Просмотр», «Макросы» и «Запись макроса»

                            Введите имя. Поскольку вы собираетесь использовать макрос для описания, используйте что-то вроде «Описание». Наконец, выберите «Все документы» в раскрывающемся списке «Сохранить макрос в».

                            Написание сценариев с помощью Microsoft Word Шаг 20

                            Написание сценариев с помощью Microsoft Word Шаг 20

                            Шаг 4. Щелкните значок клавиатуры и свяжите макрос с клавишей F3 (или другой клавишей по вашему выбору) с полем «Нажмите новую комбинацию клавиш»

                            Нажмите «Назначить» и нажмите Enter или нажмите «Закрыть».

                            В Word 2007 нажмите «Записать макрос» в правой части ленты. Сохраните макрос в том же месте, где вы сохранили предыдущий, и назовите его «Описание». Щелкните значок клавиатуры и назначьте макрос для F3

                            Написание сценариев в Microsoft Word. Шаг 21

                            Написание сценариев в Microsoft Word. Шаг 21

                            Шаг 5. Найдите значок диктофона рядом с мышью

                            Дважды нажмите Enter на клавиатуре, чтобы пропустить две строки, перейти на вкладку «Макет» («Макет страницы» в Word 2007) и изменить два отступа на ноль. Затем перейдите на «Домашнюю страницу» и щелкните значок, расположенный в правом нижнем углу раздела «Источник», чтобы открыть диалоговое окно. В разделе «Эффекты» снимите флажок «Все заглавные буквы» и нажмите «ОК».

                            В Word 2007, сняв флажок «Все заглавные буквы», вернитесь на вкладку «Разработчик» и нажмите «Остановить запись», прежде чем продолжить

                            Написание сценариев с помощью Microsoft Word Шаг 22

                            Написание сценариев с помощью Microsoft Word Шаг 22

                            Шаг 6. Откройте вкладку «Предварительный просмотр» еще раз

                            Затем нажмите «Макросы» и «Остановить запись». С этого момента клавиша F3 всегда будет пропускать две строки и переводить буквы в нижний регистр. Если вы не назначите макрос клавише, F3 не поможет при создании вашего скрипта.

                            В Word 2007 вернитесь на вкладку «Разработчик» и нажмите «Остановить запись» вместо «Макросы» и «Остановить запись»

                            Метод 5 из 5. Создание макроса для диалогов (в Word 2013 и 2016)

                            Написание сценариев в Microsoft Word. Шаг 23

                            Написание сценариев в Microsoft Word. Шаг 23

                            Шаг 1. Создайте макрос для имен персонажей

                            Персонажи и диалоги или действия обычно появляются сразу после представления и описания сцены. Имена пишутся заглавными буквами, а на следующей строке идут строки.

                            • Чтобы создать макрос для имен персонажей после описания сцены, повторите те же шаги, которые вы предприняли для создания макроса описания в Word 2013 или 2016, но:

                              • а) После изменения отступа на ноль во время записи нажмите пробел 22 раза, отметьте «Все заглавные буквы» и
                              • б) Назовите макрос «Персонаж» и назначьте его F4. Пропускайте две строчки сразу после записи.
                            • После того, как вы нажмете «Остановить запись», F4 всегда будет пропускать две строки (и перемещать курсор в правильное положение) в дополнение к заглавным буквам.
                            • В Word 2007 следуйте инструкциям в описании макроса, но поместите параметры, указанные в подшагах выше.

                            Написание сценариев с помощью Microsoft Word Шаг 24

                            Написание сценариев с помощью Microsoft Word Шаг 24

                            Шаг 2. Перейдите на вкладку «Макет» («Макет страницы» в Word 2007) и настройте поля

                            Щелкните значок в правом нижнем углу раздела «Абзац», чтобы открыть диалоговое окно. Разместите отступы 1 см перед текстом и 1,5 см после в разделе «Отступ».

                            В Word 2007 перейдите на вкладку «Разработчик». Нажмите кнопку Office в верхнем левом углу окна, чтобы получить доступ к меню параметров Word (внизу списка). Наконец, в разделе «Популярные» установите флажок «Показать разработчика»

                            Написание сценариев с помощью Microsoft Word Шаг 25

                            Написание сценариев с помощью Microsoft Word Шаг 25

                            Шаг 3. Щелкните «Просмотр», «Макросы» и «Запись макроса»

                            Введите имя. Поскольку вы собираетесь использовать макрос для создания линий, используйте что-то вроде «Диалог». Наконец, выберите «Все документы» в раскрывающемся списке «Сохранить макрос в».

                            • Щелкните значок клавиатуры и назначьте макрос для F3. Нажмите «Назначить» и нажмите Enter или нажмите «Закрыть».
                            • В Word 2007 нажмите «Записать макрос» в левой части ленты. Сохраните макрос в том же месте, где вы сохранили предыдущий, и назовите его «Описание». Щелкните значок клавиатуры и назначьте макрос нужной клавише. Например: нажмите «Нажмите новую горячую клавишу» и нажмите F5, чтобы назначить ее макросу.

                            Написание сценариев с помощью Microsoft Word Шаг 26

                            Написание сценариев с помощью Microsoft Word Шаг 26

                            Шаг 4. Найдите значок диктофона рядом с мышью

                            Один раз нажмите Enter на клавиатуре, чтобы пропустить строку и перейти на вкладку «Макет» («Макет страницы» в Word 2007), чтобы изменить два отступа на ноль. Затем перейдите на «Домашнюю страницу» и щелкните значок, расположенный в правом нижнем углу раздела «Источник», чтобы открыть диалоговое окно. В разделе «Эффекты» установите флажок «Все заглавные буквы» и нажмите «ОК».

                            • Еще раз перейдите на вкладку «Предварительный просмотр». Затем нажмите «Макросы» и «Остановить запись». С этого момента F5 всегда будет пропускать строку, переводить символы в нижний регистр и подготавливать сценарий к диалогу.
                            • В Word 2007 нажмите «Остановить запись» на вкладке «Разработчик» вместо того, чтобы нажимать «Макросы» и «Остановить запись».

                            подсказки

                            • Вы можете вручную ввести типичные термины сценария, которые используются реже, например «FADE IN:».
                            • Чтобы вставить числа на страницы, перейдите на вкладку «Вставить» и нажмите «Номер страницы», «Начало страницы» и «Номер 3 без форматирования». На вкладке «Дизайн» разместите заголовок на 5 см сверху. Снимите флажок «Другая первая страница» и удалите первую, которая не должна содержать никаких цифр.
                            • Убедитесь, что на всех страницах правильное количество строк. В Word нажмите «Формат», «Абзац», «Межстрочный интервал» и «Точно» с «12 pt». Это стандарт для сценариев фильмов, подобных тем, которые используются в Голливуде.
                            • Проверьте орфографию и грамматику. Word имеет функцию автоматической корректуры в дополнение к более ограниченным грамматическим исправлениям.
                            • Особых правил форматирования документа нет. Соблюдайте условности, установленные студией или театральной компанией, заключившей контракт с вашими услугами.

                            Уведомления

                            • Перед записью макроса ограничьте или отключите любые корректировки, которые вы хотите внести.
                            • Отключите функцию автокоррекции при написании скрипта в Word.

                            Иногда бывает задача получить какие-либо данные из word-кого документа и потом что-то с ними сделать дальше. Так же бывает и обратная задача: необходимо создать Word документ и записать в него какие-либо данные, а затем сохранить его на диск.

                            В данной заметке приведены небольшие примеры, показывающие как открыть word документ и прочитать из него текстовые данные на VBScript, а так же как создать пустой word документ, добавить в него текстовые данные, а затем записать его.

                            Пример чтения Word документа на VBScript

                            Set Wrd = CreateObject("Word.Application")
                            Set Doc = Wrd.Documents.Open("C:test.doc")
                            Set Pars = Doc.Range().Paragraphs
                            For Each Par In Pars
                              txt = Par.Range.Text
                              ' Что-то делаем с текстовыми данными из word-кого документа
                            
                            Next
                            Doc.Close
                            Wrd.Quit False
                            

                            Сначала запускаем Word в 1-й строке, во 2-й строке открываем word-кий документ (путь лучше указывать абсолютный).

                            Затем в 3-й строке получаем все параграфы, которые есть в документе и в 4-й строке в цикле проходим по всем.

                            В двух последних строках закрываем документ и закрываем сам Word, изменения не сохраняем (False).

                            Пример создания Word документа и добавления текста на VBScript

                            Set Wrd = CreateObject("Word.Application")
                            Set Doc = Wrd.Documents.Add()
                            
                            Set Par = Doc.Content.Paragraphs.Add
                            Par.Range.Text = "Пример текста"
                            Par.Range.Font.Bold = True
                            Par.Range.InsertParagraphAfter()
                            
                            Doc.SaveAs("c:Мои документыtest.docx")
                            Wrd.Quit
                            

                            Первые 2 строки запускают Word и содают новый документ.

                            Строки 4-7 добавлют параграф с текстом, выделенным жирным шрифтом.

                            Последние строки сохраняют документ под именем test.docx и закрывают word.

                            Пример создания Word документа и добавления в него таблицы

                            Set Wrd = CreateObject("Word.Application")
                            Set Doc = Wrd.Documents.Add()
                            
                            Set Table = Doc.Tables.Add(Doc.Bookmarks.Item("endofdoc").Range, 3, 5)
                            Table.Range.ParagraphFormat.SpaceAfter = 6
                            For r = 1 To 3
                              For c = 1 To 5
                                Table.Cell(r, c).Range.Text = "Ячейка " & r & " x " & c
                              Next
                            Next
                            Table.Rows.Item(1).Range.Font.Bold = True
                            Table.Rows.Item(1).Range.Font.Italic = True
                            
                            Doc.SaveAs("c:Мои документыtest.docx")
                            Wrd.Quit
                            

                            Эти простые примеры показывают минимальные возможности автоматизации чтения и записи word документов на VBScript, а дальше, можно написать более сложные программы, используя те же приемы, что используются в Visual Basic или других языках для работы с word-ом.

                            Доброго времени суток друзья. Я уже рассказывал, как можно работать с Microsoft Excel средствами PowerShell. В данной статье мы рассмотрим работу

                            PowerShell

                            с

                            Microsoft Word

                            . Как и для Excel, чтобы получить доступ к MS Word нужно использовать COM объект. Для этого используем командлет

                            New-Object

                            с параметром

                            –ComObject

                            далее сам объект к которому хотим получить доступ, в нашем случае это

                            Word.Application

                            .

                              
                                #Создаем новый объект WORD
                                $word = New-Object -ComObject Word.Application
                              
                            

                            После создания объекта обращаемся к свойству

                            Visible

                            и переключаем его в

                            TRUE

                            чтобы видеть работу скрипта непосредственно в самом

                            MS Word

                            а не в фоновом режиме.

                              
                                #Видимый режим вставки, по умолчанию FALSE
                                $word.Visible = $True
                              
                            

                            Далее необходимо создать сам документ для этого обращаемся к свойству

                            Documents

                            и его методу

                            Add()

                            .

                              
                                #Создаем новый документ
                                $doc = $word.Documents.Add()
                              
                            

                            Обратимся к свойству

                            Selection

                            для работы с текущим документом, далее мы будем использовать его для форматирования нашего документа.

                              
                                #Выбираем открывшийся документ для работы
                                $Selection = $word.Selection
                              
                            

                            Задаем начальные настройки для документа допустим отступы со всех сторон.

                              
                                #Устанавливаем отступы для документа
                                $Selection.Pagesetup.TopMargin = 50
                                $Selection.Pagesetup.LeftMargin = 50
                                $Selection.Pagesetup.RightMargin = 50
                                $Selection.Pagesetup.BottomMargin = 50
                              
                            

                            Установим строчный интервал сверху и снизу.

                              
                                #Интервал отступов сверху и снизу
                                $Selection.ParagraphFormat.SpaceBefore = 0
                                $Selection.ParagraphFormat.SpaceAfter = 0
                              
                            

                            Подготовительные работы закончены, теперь можем заполнять наш документ. Укажем что наш первый абзац будет по центру для этого воспользуемся свойством ParagraphFormat и его свойством

                            Aligment

                            .

                              
                                #Выравнивание по центру
                                $Selection.ParagraphFormat.Alignment = 1
                              
                            

                            Далее создаем таблицу с одной строкой и одной ячейкой которую зальем черным цветом и разместим пользовательскую картинку.

                              
                                #Добавляем таблицу
                                $Table = $Word.ActiveDocument.Tables.Add($Word.Selection.Range, 1, 1)
                            
                                #Устанавливаем черный цвет заливки ячейки
                                $Table.Cell(1,1).Shading.BackgroundPatternColor = 0
                            
                                #Вставляем картинку в ячейку таблицы
                                $Table.Cell(1,1).Range.InlineShapes.AddPicture("D:Tempbezramok-tlt.png")
                            
                                #Конец таблицы, начать новую строку
                                $Selection.EndKey(6, 0)
                              
                            

                            Далее переходим на новую строчку документа воспользовавшись методом

                            TypeParagraph()

                            .

                              
                                #Новый параграф
                                $Selection.TypeParagraph()
                              
                            

                            Далее установим нужные настройки для нашего заголовка.

                              
                                #Шрифт написания
                                $Selection.Font.Name = "Times New Roman"
                            
                                #Размер шрифта
                                $Selection.Font.Size = 18
                              
                            

                            Как видно из примера мы установили шрифт

                            Time New Roman

                            и размер шрифта

                            18

                            , далее вставляем текст.

                              
                                #Текст заголовка
                                $Selection.TypeText("Работаем с Microsoft Word при помощи PowerShell")
                              
                            

                            Для следующего текста поменяем настройки шрифта и размер и вид, а также выровняем текст по ширине документа.

                              
                                #Выравнивание по ширине листа
                                $Selection.ParagraphFormat.Alignment = 3
                            
                                #Устанавливаем новые значения размера шрифта
                                $Selection.Font.Name = "Arial"
                                $Selection.Font.Size = 12
                            
                                #Пишем курсивом
                                $Selection.Font.Italic = $true
                              
                            

                            Далее добавляем новый текст в наш документ.

                              
                                #Добавляем следующий текст
                                $Selection.TypeText("Windows PowerShell — расширяемое средство автоматизации от Microsoft с открытым исходным кодом")
                              
                            

                            Так как для следующего текста нам не нужен курсив, то отключаем его.

                              
                                #отключаем курсив
                                $Selection.Font.Italic = $false
                              
                            

                            Далее создаем настройки для следующего текста, выправным его по центру и изменим цвет на темно-зеленый, а также выделим жирным.

                              
                                #Вставляем заголовок по центру
                                $Selection.ParagraphFormat.Alignment = 1
                            
                                #Устанавливаем новые значения размера шрифта
                                $Selection.Font.Name = "Arial"
                                $Selection.Font.Size = 18
                            
                                #Делаем цвет текста темно-зеленым
                                $Selection.Font.Color = "wdColorDarkGreen"
                            
                                #Выделяем жирным
                                $Selection.Font.Bold = $True
                            
                                #Следующий текст в нашем документе
                                $Selection.TypeText("Добавляем картинку из файла ")
                              
                            

                            Далее вставляем картинку в документ по центру, для этого используем свойство

                            InlineShapes

                            и его метод

                            AddPicture()

                            передав путь до картинки.

                              
                                #Вставляем картинку из файла
                                $Selection.InlineShapes.AddPicture("D:Tempword.jpg")
                              
                            

                            Далее отменяем центрирование и меняем цвет текста на черный.

                              
                                #Делаем цвет текста черным
                                $Selection.Font.Color = 0
                            
                                #Отменяем жирный
                                $Selection.Font.Bold = $False
                              
                            

                            Устанавливаем новые настройки для следующего текста.

                              
                                #Настройки размера шрифта для нового текста
                                $Selection.Font.Name="Times New Roman"
                                $Selection.Font.Size=12
                              
                            

                            Далее создадим таблицу с тремя столбцами в которую заполним с помощью

                            PowerShell

                            .

                              
                                #Добавляем таблицу
                                $Table = $Word.ActiveDocument.Tables.Add($Word.Selection.Range, 1, 3)
                            
                                #Ручной вариант форматирования таблицы
                                # $Table.Range.Style = "Table Grid"
                                # $Table.Borders.InsideLineStyle = 1
                                # $Table.Borders.OutsideLineStyle = 1
                            
                                #Заполняем шапку таблицы
                                $Table.Cell(1,1).Range.Text = "№"
                                $Table.Cell(1,2).Range.Text = "Name"
                                $Table.Cell(1,3).Range.Text = "DysplayName"
                            
                                #Счетчики для генерации таблицы
                                $i = 2
                                $counter = 1
                            
                                #Получаем список всех процессов на компьютере
                                $srv = Get-Service a*
                            
                                #Записываем полученые данные в ячейки таблицы
                                foreach ($arr in $srv)
                                {
                                $Table.Rows.Add()
                                $Table.Cell($i,1).Range.Text = $counter
                                $Table.Cell($i,2).Range.Text = $arr.Name
                                $Table.Cell($i,3).Range.Text = $arr.DisplayName
                            
                            
                                #инкрементируем счетчики
                                $i = $i + 1
                                $counter = $counter + 1
                                }
                            
                                #Автоформатирование таблицы
                                $Table.AutoFormat(20)
                            
                                #Конец таблицы, начать новую строку
                                $Selection.EndKey(6, 0)
                              
                            

                            Здесь нужно отметить, что ячейки таблицы начинаются с

                            1

                            . Для генерации новой строки нужно использовать свойство Rows и его метод

                            Add()

                            . Для удобства форматирования таблицы используем метод

                            AutoFormat()

                            передав число (это идентификатор шаблона форматирования таблицы). Для перехода от таблицы к обычному документу используем метод

                            EndKey(6, 0)

                            .

                            Далее создаем настройки для нового текста, выровняем все по левому краю и добавим гиперссылок в наш документ.

                              
                                #Вставляем заголовок по центру
                                $Selection.paragraphFormat.Alignment = 0
                            
                                #Размер шрифта
                                $Selection.Font.Size=14
                            
                                #Текст
                                $Selection.TypeText("Урок создал")
                            
                                #Новый параграф
                                $Selection.TypeParagraph()
                            
                                #Размер шрифта
                                $Selection.Font.Size=12
                            
                                #Гиперссылка сайта
                                $Selection.Hyperlinks.Add($Selection.Range,"http:#bezramok-tlt.ru")
                            
                                #Новый параграф
                                $Selection.TypeParagraph()
                            
                                #Гиперссылка почты
                                $Selection.Hyperlinks.Add($Selection.Range,"mailto:bezramok-tlt@mail.ru")
                            
                                #Новый параграф
                                $Selection.TypeParagraph()
                            
                                #Текст
                                $Selection.TypeText("Админ")
                            
                                #Новый параграф
                                $Selection.TypeParagraph()
                            
                                #Размер шрифта
                                $Selection.Font.Size=10
                            
                                #Текст
                                $Selection.TypeText("Дата: " + $date)
                              
                            

                            Как вы заметили мы использовали свойство

                            Hyperlinks

                            и его метод

                            Add()

                            в который передали

                            URL

                            для гиперссылки.

                            Далее сохраняем документ (СохранитьКак) указываем путь куда будем сохранять наш файл, закрываем сам документ, закрываем само приложение MS Word.

                              
                                #СохранитьКак указываем путь куда и имя файла
                                $doc.SaveAs([ref]"D:tempPsWord.docx")
                            
                                #Закрываем документ
                                $doc.Close()
                            
                                #Закрываем приложение
                                $word.Quit()
                              
                            

                            Я постарался собрать на мой взгляд основные действия для заполнения документа – это форматирование текста, изменение размера текста, шрифта, цвета. Создание таблиц, заполнение таблицы графически и текстовым материалом, а также заливка ячейки цветом.

                            Вот таким способом можно создавать документы

                            MS Word

                            с помощью

                            PowerShell

                            .

                            Скрипт PowerShell работа с MS Word целиком

                              
                                #Получаем текущую дату
                                $date = Get-Date
                            
                                #Создаем новый объект WORD
                                $word = New-Object -ComObject Word.Application
                            
                                #Видимый режим вставки, по умолчанию FALSE
                                $word.Visible = $True
                            
                                #Создаем новый документ
                                $doc = $word.Documents.Add()
                            
                                #Выбираем открывшийся документ для работы
                                $Selection = $word.Selection
                            
                                #Устанавливаем отступы для документа
                                $Selection.Pagesetup.TopMargin = 50
                                $Selection.Pagesetup.LeftMargin = 50
                                $Selection.Pagesetup.RightMargin = 50
                                $Selection.Pagesetup.BottomMargin = 50
                            
                            
                                #Интервал отступов сверху и снизу
                                $Selection.ParagraphFormat.SpaceBefore = 0
                                $Selection.ParagraphFormat.SpaceAfter = 0
                            
                            
                                #Выравнивание по центру
                                $Selection.ParagraphFormat.Alignment = 1
                            
                                #Добавляем таблицу
                                $Table = $Word.ActiveDocument.Tables.Add($Word.Selection.Range, 1, 1)
                            
                                #Устанавливаем черный цвет заливки ячейки
                                $Table.Cell(1,1).Shading.BackgroundPatternColor = 0
                            
                                #Вставляем картинку в ячейку таблицы
                                $Table.Cell(1,1).Range.InlineShapes.AddPicture("D:Tempbezramok-tlt.png")
                            
                            
                                #Конец таблицы, начать новую строку
                                $Selection.EndKey(6, 0)
                            
                                #Новый параграф
                                $Selection.TypeParagraph()
                            
                                #Шрифт написания
                                $Selection.Font.Name = "Times New Roman"
                            
                                #Размер шрифта
                                $Selection.Font.Size = 18
                            
                                #Текст заголовка
                                $Selection.TypeText("Работаем с Microsoft Word при помощи PowerShell")
                            
                                #Переходим на новую строку
                                $Selection.TypeParagraph()
                            
                                #Выравнивание по ширине листа
                                $Selection.ParagraphFormat.Alignment = 3
                            
                                #Устанавливаем новые значения размера шрифта
                                $Selection.Font.Name = "Arial"
                                $Selection.Font.Size = 12
                            
                                #Пишем курсивом
                                $Selection.Font.Italic = $true
                            
                                #Добавляем следующий текст
                                $Selection.TypeText("Windows PowerShell — расширяемое средство автоматизации от Microsoft с открытым исходным кодом")
                            
                                #отключаем курсив
                                $Selection.Font.Italic = $false
                            
                                #Новый параграф
                                $Selection.TypeParagraph()
                            
                                #Новый параграф
                                $Selection.TypeParagraph()
                            
                                #Вставляем заголовок по центру
                                $Selection.ParagraphFormat.Alignment = 1
                            
                                #Устанавливаем новые значения размера шрифта
                                $Selection.Font.Name = "Arial"
                                $Selection.Font.Size = 18
                            
                                #Делаем цвет текста темно-зеленым
                                $Selection.Font.Color = "wdColorDarkGreen"
                            
                                #Выделяем жирным
                                $Selection.Font.Bold = $True
                            
                                #Следующий текст в нашем документе
                                $Selection.TypeText("Добавляем картинку из файла ")
                            
                                #Вставляем картинку из файла
                                $Selection.InlineShapes.AddPicture("D:Tempword.jpg")
                            
                                #Делаем цвет текста черным
                                $Selection.Font.Color = 0
                            
                                #Отменяем жирный
                                $Selection.Font.Bold = $False
                            
                                #Новый параграф двойной отступ
                                $Selection.TypeParagraph()
                                $Selection.TypeParagraph()
                            
                                #Настройки размера шрифта для нового текста
                                $Selection.Font.Name = "Times New Roman"
                                $Selection.Font.Size = 14
                            
                                $Selection.TypeText("Создание таблицы в Microsoft Word средствами PowerShell")
                            
                                #Новый параграф
                                $Selection.TypeParagraph()
                            
                                #Новый параграф
                                $Selection.TypeParagraph()
                            
                                #Настройки размера шрифта для нового текста
                                $Selection.Font.Name="Times New Roman"
                                $Selection.Font.Size=12
                            
                                #Добавляем таблицу
                                $Table = $Word.ActiveDocument.Tables.Add($Word.Selection.Range, 1, 3)
                            
                                #Ручной вариант форматирования таблицы
                                # $Table.Range.Style = "Table Grid"
                                # $Table.Borders.InsideLineStyle = 1
                                # $Table.Borders.OutsideLineStyle = 1
                            
                                #Заполняем шапку таблицы
                                $Table.Cell(1,1).Range.Text = "№"
                                $Table.Cell(1,2).Range.Text = "Name"
                                $Table.Cell(1,3).Range.Text = "DysplayName"
                            
                                #Счетчики для генерации таблицы
                                $i = 2
                                $counter = 1
                            
                                #Получаем список всех процессов на компьютере
                                $srv = Get-Service a*
                            
                                #Записываем полученые данные в ячейки таблицы
                                foreach ($arr in $srv)
                                {
                                $Table.Rows.Add()
                                $Table.Cell($i,1).Range.Text = $counter
                                $Table.Cell($i,2).Range.Text = $arr.Name
                                $Table.Cell($i,3).Range.Text = $arr.DisplayName
                            
                            
                                #инкрементируем счетчики
                                $i = $i + 1
                                $counter = $counter + 1
                                }
                            
                                #Автоформатирование таблицы
                                $Table.AutoFormat(20)
                            
                                #Конец таблицы, начать новую строку
                                $Selection.EndKey(6, 0)
                            
                                #Новый параграф
                                $Selection.TypeParagraph()
                            
                                #Вставляем заголовок по центру
                                $Selection.paragraphFormat.Alignment = 0
                            
                                #Размер шрифта
                                $Selection.Font.Size=14
                            
                                #Текст
                                $Selection.TypeText("Урок создал")
                            
                                #Новый параграф
                                $Selection.TypeParagraph()
                            
                                #Размер шрифта
                                $Selection.Font.Size=12
                            
                                #Гиперссылка сайта
                                $Selection.Hyperlinks.Add($Selection.Range,"http:#bezramok-tlt.ru")
                            
                                #Новый параграф
                                $Selection.TypeParagraph()
                            
                                #Гиперссылка почты
                                $Selection.Hyperlinks.Add($Selection.Range,"mailto:bezramok-tlt@mail.ru")
                            
                                #Новый параграф
                                $Selection.TypeParagraph()
                            
                                #Текст
                                $Selection.TypeText("Админ")
                            
                                #Новый параграф
                                $Selection.TypeParagraph()
                            
                                #Размер шрифта
                                $Selection.Font.Size=10
                            
                                #Текст
                                $Selection.TypeText("Дата: " + $date)
                            
                                #Новый параграф
                                $Selection.TypeParagraph()
                            
                                #СохранитьКак указываем путь куда и имя файла
                                $doc.SaveAs([ref]"D:tempPsWord.docx")
                            
                                #Закрываем документ
                                $doc.Close()
                            
                                #Закрываем приложение
                                $word.Quit()
                              
                            

                            Понравилась статья? Поделить с друзьями:
                          1. Word текст несколько листов
                          2. Word текст не стирается
                          3. Word текст не помещается
                          4. Word текст не переносится на следующую строку
                          5. Word текст не до конца строки