Create programs in word

Its undeniable that creating a flowchart in Lucidchart and then inserting it into your Microsoft Office applications using the Add-Ins is the most efficient way to incorporate flowcharts into your Word documents. However, its still possible to make a flowchart in Word directly and this helpful guide will show you how.

1. Open a blank document in Word

2. Add shapes

To begin adding shapes to your flowchart in Word, you have two options. Begin by going to the Insert tab within the Ribbon and choose SmartArt or Shapes. SmartArt graphics are pre-made collections of shapes within a gallery. The Shapes tool provides a basic selection of shaped objects that can be inserted and edited onto the document.

Adding symbols via SmartArt in Word

A gallery box will pop up when you select SmartArt from the Insert tab. We recommend clicking Process for flowchart-specific options from the left panel in the dialog box, but keep in mind that you are by no means limited to this option and are free to use whatever SmartArt graphic is best for your specific needs. You will then click the SmartArt selection you want to use and a preview of that flowchart graphic will appear in the right panel, along with an explanation of its logic. Click OK to insert the selected graphic into your document.

How do you create a program in Word?

To replace your graphic with SmartArt at any time, select it and press Delete. You can then click the SmartArt Graphics (Insert > SmartArt) and choose a different chart type. If you prefer to change the layout of a SmartArt graphic, select the shape(s) and select a new style from the Design tab within the Ribbon menu. Rest assured that you can edit the SmartArt chart layout at any time without losing any text.

From the Design tab, you can then continue to add flowchart shapes and connect them with lines until your flowchart is ready. If you find yourself lacking in shape options, you will need to manually add a shape from within the Design tab. To do this, select the shape (or entire chart in some cases) nearest to where you want to add a new shape. Then select Add a Shape.

Adding symbols via Shapes in Word

From the Insert tab within the Ribbon, select a flowchart shape from the dropdown gallery. You can then click and drag it to the size you want on the page to place it. Continue to add shapes and lines to complete your flowchart.

How do you create a program in Word?

3. Add text

Add text to a SmartArt graphic by clicking the filler text and begin typing. Depending on how much text you add, the shape and font will automatically resize to fit.

For a Shape, add text by double-clicking the object and begin typing. To customize the font, use the toolbox that pops up when a desired shape is selected.

How do you create a program in Word?

4. Add lines

To draw lines between shapes, click Insert > Shapes and select a line style. Then click and drag on the page to add a line.

5. Format shapes and lines

To really make this flowchart stand out in Word, youll want to do some final formatting. You wont have as many options as you would in Lucidchart, but theres still some significant room for customization when making a flowchart in Word.

For some of the simplest editing options, a menu will appear with basic editing options when you right-click on an object.

How do you create a program in Word?

To edit text layout click the Layout Options icon that appears when you right-click a text box and pick your preferred layout. You can also view the rest of the option when you click See More.

Move a shape or lines anywhere on the Word document by simply clicking and dragging. If youre trying to resize the image, just click and drag from a corner or edge and use the handle icon to rotate the shape.

If you select a SmartArt graphic:

Change the design of your shapes by selecting your objects and choosing an option from the two new tabs in the Ribbon, Format and Design.

How do you create a program in Word?

If you select a shape:

When changing the design of an object that was placed using Shapes, the Format tab will appear when you select the flowchart shape to begin your modifications.

Pieter van der Westhuizen

Posted on Friday, March 28th, 2014 at 9:20 am by .

It’s been close to two years since we’ve discussed the release of Office 2013 and the new web-based object model for Office, called Napa, which allows developers to build Office add-ins using HTML, CSS and JavaScript.

We thought that after we investigated how to create customization for Google Docs and Google Sheets, it is about time we tackle the Napa Office 365 development tools again. We’ll create a Task Pane app for Microsoft Word, similar to the one we created for Google Docs that will allow the user to shuffle either the selected words, sentences or paragraphs in a Microsoft Word document.

  • Creating a Word App for Office 365
  • Building the Word app UI
  • Shuffling the selected text using JavaScript

Creating an Office App for Word

Before you can start creating and testing your Office App, you need to first provision a Developer site. I won’t go into the steps involved in creating such a site as this article on MSDN does a good job of explaining the necessary steps.

You have two options when creating an app for Microsoft Office, the first is via the Napa development tools inside your browser and the second is using Office Developer Tools for Visual Studio 2013.

Creating a Word app using the Napa development tools

After the Developer site has been provisioned, open it in your browser. You should be presented with the following options:

Creating an app using the Napa development tools

Click on the “Build an app” button. This will redirect your browser to www.napacloudapp.com, then click on the “Add New Project” button in order to create a new App.

Click on the 'Add New Project' button in order to create a new App.

A modal dialog will be shown; prompting you to select the type of app you would like to build. Our app will target Microsoft Word, so select Task pane app for Office from the list.

Select Task pane app for Office from the list.

This will create a project containing all the necessary HTML, CSS and JavaScript files. Because we need the app to run inside Microsoft Word, we have to set this in the project properties. Click on the Properties item in the left hand navigation menu and change the application to launch to Microsoft Word.

Click on the Properties item and change the application to launch to Microsoft Word.

You have a choice to either edit the project via the browser or open the project in Visual Studio by clicking on the “Open in Visual Studio” item in the left-hand navigation bar. This will download and open the project in Visual Studio.

Creating a Word app using Visual Studio 2013

You also have the choice of creating a new app by using Visual Studio 2013. Start by creating a new Apps for Office project, by selecting the project template in Visual Studio.

Select the App for Office project template in Visual Studio.

Select Task pane when prompted to choose which app you’d want to create.

Select Task pane when prompted to choose which app you'd want to create.

We’ll only be targeting Microsoft Word with this app, so only check its checkbox when asked in which Office application your task pane should reflect in.

Check the Word checkbox when asked in which Office application your task pane should appear.

The project template will add all the necessary files needed to create the MS Word app and your Solution Explorer layout will appear, which will look similar to the following:

The Solution Explorer layout

If you’ve opted to create your Word app using the Napa tools, the project layout and files will be exactly the same as when creating the project directly from Visual Studio.

Building the app UI

The Home.html file contains a base layout, which already implements the correct styling for Office. This style is defined inside the Office.css and Home.css files. Add any of your own CSS styles, that you would like to use for the app inside the Home.css file.

The app will be a task pane running inside Microsoft Office Word and will look similar to the following image:

The app will be a task pane running inside Microsoft Office Word.

The UI is created by specifying the following HTML markup inside the Home.html file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <title>WordShuffleIt</title>
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>
 
    <link href="../../Content/Office.css" rel="stylesheet" type="text/css" />
    <script src="https://appsforoffice.microsoft.com/lib/1.1/hosted/office.js" type="text/javascript"></script>
 
    <link href="../App.css" rel="stylesheet" type="text/css" />
    <script src="../App.js" type="text/javascript"></script>
 
    <link href="Home.css" rel="stylesheet" type="text/css" />
    <script src="Home.js" type="text/javascript"></script>
</head>
<body>
    <!-- Page content -->
    <div id="content-header">
        <div class="padding">
            <h1>The Word Shuffler</h1>
        </div>
    </div>
    <div id="content-main">
        <div class="padding">
            <p><strong>This app shuffles your selection in MS Word.</strong></p>
            <p>Please select how you would like to shuffle the current selection:</p>
            <p>
                <input type="radio" name="shuffleType" value="Words" checked>Words
            </p>
            <p>
                <input type="radio" name="shuffleType" value="Sentences">Sentences
            </p>
            <p>
                <input type="radio" name="shuffleType" value="Paragraphs">Paragraphs
            </p>
            <button id="do-stuff">Shuffle It!</button>
        </div>
    </div>
</body>
</html>

In the Html mark-up, we added a short instruction text, three radio buttons and a button.

Shuffling the selected text using JavaScript

We define all our app logic inside the Home.js file. The project template created some initial boilerplate code inside this file. The most important item for this app is the initialize function. This function runs as soon as the app is opened inside Word.

Add a click handler for the do-stuff button which will invoke the getDataFromSelection function when the user clicks the button.

Office.initialize = function (reason) {
    $(document).ready(function () {
        app.initialize();
        $('#do-stuff').click(getDataFromSelection);
    });
};

The getDataFromSelection function in turn will check which radio button is selected and store the value inside the shuffleType variable. We’ll then get the currently selected text inside MS Word by calling the getSelectedDataAsync function, the selected text is then passed into the shuffleSelectedText function.

function getDataFromSelection() {
    var shuffleType = $('input[name=shuffleType]:checked').val();
    Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
		function (result) {
		    if (result.status === Office.AsyncResultStatus.Succeeded) {
		        shuffleSelectedText(result.value, shuffleType);
		    } else {
		        app.showNotification('Error:', result.error.message);
		    }
		}
	);
}

The shuffleSelectedText function will split the selected text based on the type of shuffle the users selected, which could be words, sentences or paragraphs. The Office apps object model does not provide a function to determine whether paragraphs are selected, so we’ll simply split the selected text by the newline character. After the selected text is split according to the user’s selection, we pass it into the shuffle function in order to return an array with the shuffled selection.

We then override the selection with the shuffled text by using the setSelectedDataAsync function and show a notification to the user indicating how many words, sentences or paragraphs where shuffled.

The code for the shuffleSelectedText and shuffle function is as follows:

function shuffleSelectedText(text, shuffleType) {
    var shuffledArray;
    var shuffledText = "";
    if (shuffleType == "Words") {
        shuffledArray = shuffle(text.split(' '));
        for (var i = 0; i < shuffledArray.length; i++) {
            shuffledText += shuffledArray[i] + ' ';
        }
    } else if (shuffleType == "Sentences") {
        shuffledArray = shuffle(text.match(/[^.!?]+[.!?]+/g));
        for (var i = 0; i < shuffledArray.length; i++) {
            shuffledText += shuffledArray[i];
        }
    } else if (shuffleType == "Paragraphs") {
        shuffledArray = shuffle(text.split(/rn|r|n/g));
        for (var i = 0; i < shuffledArray.length; i++) {
            shuffledText += shuffledArray[i] + 'rn';
        }
    }
    Office.context.document.setSelectedDataAsync(shuffledText);
    app.showNotification("Shuffled " + shuffledArray.length + " " + shuffleType);
}
 
function shuffle(array) {
    var currentIndex = array.length
      , temporaryValue
      , randomIndex
    ;
    while (0 !== currentIndex) {
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }
 
    return array;
}

To test the app, build and run the project. Microsoft Word will open with the app loaded inside a task pane and will resemble the following screenshot:

The Word Shuffler app loaded inside a task pane in Microsoft Word.

Thank you for reading. Until next time, keep coding!

Available downloads:

Word Shuffler app

The Microsoft Office suite is one of the most popular office solutions. From Word and Excel to PowerPoint – the practical applications for writing, calculating, and presenting have been proving their worth for years. But many users are not even aware of the range of features that they provide. For instance, MS Office programs include a function that allows you to create, save, and execute macros in order to automate certain tasks and processes. Especially for regularly recurring workflows, this feature lets you save valuable time and effort.

But what role do macros play in Word and how do these command sequences work exactly? Also find out how to create macros in Word and integrate them into your documents.

Contents

  1. What is a Word macro?
  2. How Do Macros Work in Word?
  3. Creating Macros in Word: How it Works
    1. Recording Word Macros Executed by Button
    2. Creating Word Macros Executed via Key Combination
    3. Executing Word Macros
    4. Adding macro buttons to a Word tab ribbon
    5. Importing Existing Macros in Word
  4. Word Macros: Examples of Useful Command Sequences
    1. Word Macro for Automatically Determining the Average Sentence Length
    2. Word Macro Example: Correcting Transposed Letters
    3. Macro Code for Removing All Hyperlinks

What is a Word macro?

Macros are considered a standard feature in programming as well as the use of computer programs. They are basically subprograms that developers and users can create to save sequences of commands or operating instructions, which can then be started with a simple action. When faced with many regularly recurring tasks, Microsoft Word is typically an application that benefits from the option to automate work steps.

For this reason, the Editor (as well as Access, Excel or PowerPoint, for example) include an integrated tool for recording and executing custom Word macros. The script language Visual Basic for Applications (VBA), likewise developed by Microsoft, serves as the recording language here.

Note

The event-driven programming language VBA replaced the mutually incompatible macro languages of the various Microsoft Office programs in the mid-1990s. Thanks to this standardized solution, cross-program command chains can also be created and run to transfer data from a Word document into an Excel table with a single click, for example.

How Do Macros Work in Word?

Creating macros in Word may sound like a task for experienced programmers at first. After all, writing new program code in a special programming language is not often among the core skills of the average Word user. However, the fact that creating and using Word macros is possiblewithout any programming knowledge at all is thanks to the integrated macro tool. Known as a macro recorder, this tool makes writing code completely unnecessary. To create a new macro, all the user has to do is start recording, perform the desired operating steps and commands, and then stop the recording again when the sequence is finished. The VBA code for Word macros is generated automatically; no further action is required on the part of the user.

Note

With the Visual Basic Editor, the Microsoft Office tools have integrated their own VBA development environment that allows the code of recorded macros to be viewed and edited.

You can also assign each new macro in Word with a unique key combination or button that allows the corresponding command sequence to be run at any time. In the case of buttons, these can be added to the toolbar for quick access, enabling you to start a macro with a single click. If the Word macro created is to be available in all documents, save it in the template file Normal.dotm, which is used by Word as the general template for all new text projects.

Creating Macros in Word: How it Works

If you would like to configure your own automated sequences for your Word documents, but lack the technical knowledge in the programming language VBA, you should use the option to create macros in Word using the recorder. You can find the macro tools as standard under the “Macros” section in the “View” tab. In order to make it easier to create and manage Word macros, however, it is advisable to activate the developer tools which provide you access to the Visual Basic Editor, among other features. This optional toolbox can be unlocked as follows:

  1. Open the “File” tab.
  2. Click on “Options”.
  3. Switch to the “Customize the Ribbon” section and place a checkmark in the “Developer” box (under “Main Tabs”).
Word 2016: “Customize the Ribbon” in the Word options
You can remove the developer tools from the Word ribbon at any time by deactivating the checkbox.

As soon as you have activated the “Developer” tools in the Word options, the tabunder the same name will automatically be added to the user interface. When you click on it, you will see the section for creating and managing macros in the far left of the toolbar. Find out in the following step-by-step guide how to create your own macros in Word using this quick-access menu and how you can run them at a later time.

Recording Word Macros Executed by Button

The typical solution for a new macro in Word is one that can be run by clicking a button. If you would like to create such a macro using the developer tools, first click on the “Developer” tab and then select the option “Record Macro”:

Word 2016: “Developer” tab
To open the menu for recording new Word macros, you can also press the [Alt], [L], and [R] keys consecutively.

Now enter a name for the macro and select the document you wish to create the macro for under “Store macro in:”. If you would like to create a cross-program macro, simply select the option “All Documents (Normal.dotm)”. To enable the macro to be executed in Word using a button, finally click on “Button”:

The “Record Macro” menu in Word 2016
You have the option to add individual information about the Word macro you want to create under “Description”.

Select the macro you wish to create in the left window and click on “Add”, making it also selectable in the right window. Click on it here again and then press the “Change” button. You can now assign your new Word macro any icon you wish:

Adjusting the quick-access toolbar in Word 2016
When assigning the button for the new macro, you also have the option of adding it to all Word documents (standard) or for a certain document only.

Confirm your desired button by clicking on “OK” twice. Now perform the actions you want to save in the macro. Word will record your mouse clicks as well as key strokes. However, the recorder will not save any movements or highlighting with the mouse. So if you want to select some text, for example, you will need to use the keyboard (hold down the [Shift] key and use the arrow keys).

Once you have finished the sequence for the macro, you can stop the recording via “Stop Recording”:

The “Developer” tab in Word 2016
You can also pause the recording for the Word macro temporarily: Simply use the “Pause Recording” button in the toolbar.

The key for the new Word macro will automatically be added to the toolbar for quick access:

Microsoft Word 2016: Quick-access toolbar
The quick-access toolbar also contains as standard the buttons for saving the current Word document or reversing changes.

Creating Word Macros Executed via Key Combination

You can create a Word macro that can be started using a unique key combination in essentially the same way as for macro buttons: Start the process using the “Record Macro” button in the macro menu under “Developer”, enter a suitable name, and decide whether you want to make the macro available in all documents or only in a certain project. In the final step before beginning the recording, you should choose the “Keyboard” option in order to open the menu for new hotkeys:

The “Record Macro” Word menu
If you choose a name for a new macro which already exists, Word will ask whether you wish to replace the original macro.

In the “Customize Keyboard” menu that then appears, select the macro under “Commands”. Next, click on the “Press new shortcut key” field with the left mouse button and press your desired key combination. Here it is important to press these keys simultaneously. In the following Word macro example, we used the [Ctrl], [Shift], and [#] keys.

Word 2016: “Customize Keyboard” menu
Word will tell you whether a chosen key combination already exists or is not yet assigned – as in this example.

Under “Save changes in”, you can define whether the key combination should be valid universally (“Normal”) or only for a certain Word document; to confirm your choice, click on the “Assign” button. As soon as you close the menu, the macro recording will start.

Executing Word Macros

Once you have created a macro, you can start it at any time using the defined execution option. You only need to use the define key combination or click on the corresponding button in the quick-access menu (in the top left). You can also run your Word macros using the macro list by following the steps below:

  1. Click on the “Macros” button under the “Developer” tab or alternatively on “Macros” in the menu under the “View” tab, and then on “View Macros”.
  2. Select the desired macro from the list using a left mouse click.
  3. Now press “Run”.
List of available macros in Word 2016
Once you have activated the developer tools, you can open the selected Word macro in the Visual Basic Editor by clicking on “Edit”.

Adding macro buttons to a Word tab ribbon

If the macro icon is too small for you in the quick-access toolbar or if you would like to add a button for a macro executable via key combination, you can also integrate a macro button into the ribbon of any tab. To do so, simply create a user-defined group for the tab and add the desired macro to it. You can do both in the “Customize Ribbon” menu in the Word options (accessibly via “File” -> “Options”).

Creating a user-defined group:

In the right window under “Customize Ribbon”, select the tab in which you wish to create the new group and then click on the “New Group” button. In addition to the standard groups here, the entry “New Group (User-Defined)” will now appear. Click on this and then press “Rename” to give the group a suitable name as well as an icon:

Word 2016: Customizing the ribbon for the “Start” tab
World will only display the selected symbol if the width of the program window is reduced and the group is collapsed for this reason.

Integrating a Word macro into a user-defined group:

After creating a user-defined group for a tab’s ribbon, you can now add any number of Word macros to this group. First click on the “Macros” option in the left menu section under “Choose commands from:” and then on the Word macro you wish to integrate. In the right menu window, now click on the user-defined group before finally pressing the “Add” button:

Adding Word macros to a tab
If you would like to remove a macro from a user-defined ribbon group again, select it in the right menu window and then click on the “Remove” button.

Close the Word options and open the tab you added the macro button to. You should now see this in the group you created in the ribbon:

Word 2016: Customized ribbon
In standard tabs, new groups are typically added to the right of existing groups. But you can also adjust the order and position the button elsewhere.

Importing Existing Macros in Word

You may also find yourself in the situation in which you already have VBA macros, but they are not available in your Word installation. This could be the case, for instance, if you created these macros on another device or received them from another person. Plus, there are various online sources where you can find a wide range of macros. Microsoft Word offers you the option to import ready-made command chains for use in your program. The tool for this is the Visual Basic Editor mentioned earlier. It can be opened via the key combination [Alt] + [F11] or alternatively using the “Developer” tab.

The next steps depend on whether you are importing a finished macro file or pure macro code.

Importing ready-made macro files (.frm, .bas, .cls):

If you have a complete macro as a file, you can import it into your Word installation in just a few steps. First, select the document you want to add the macro to in the Project Explorer. If you can’t find the explorer in the code editor, you can open it by selecting the “View” tab and pressing the “Project Explorer” menu item. In the file manager, now click on your current or another Word project if the macro should only be applied to one document. If you select the project “Normal”, the Word macro will be imported for all documents:

Project Explorer in the Visual Basic Editor
When you no longer need the Project Explorer, you can close it at any time by clicking on the cross in the top right.

To import the macro, click on “File” and then “Import File”. Specify the storage location for the macro file and press “Open” to start the import process.

The “Import File” option in the Visual Basic Editor
If you have created a Word macro, you can also export it as a file here using the button under the same name.

Importing macro code:

If you only have the code for a certain macro, other steps have to be taken for importing. Here too, you start by selecting the document you wish to add the automatic command sequence to. Open the explorer and double-click on the entry “ThisDocument” (in the subfolder “Microsoft Word Objects”) for the respective document or under “Normal” (to save the macro in the universal template):

Microsoft Word 2016: Project Explorer
When you select the project “Normal”, Word will save the macro in the universal template Normal.dotm.

In the code window that appears next, copy the macro code and then click on the “Save” button. If you selected a specific Word document in the previous step, you will be notified that you will have to save it as a “Word document with macros”. Then click on “No” and select the corresponding entry under the “File Type” list. Finally, click on “Save” to generate the new file format:

Changing the Word file type
To save an imported macro in the current Word document, you will need to change the format of your current document. When saving in the universal template, however, this is not necessary.

Word Macros: Examples of Useful Command Sequences

Now that you know what a Word macro is and how to use macros in Word (creating, running, and importing macros), we can explain the purpose of these command chains for automation in Microsoft’s text editor using a number of specific Word macro examples.

Word Macro for Automatically Determining the Average Sentence Length

There are various web tools you can use to analyze your texts – such as to ascertain the average length of your sentences. Using the right macro, you can also find this out directly in Word. The following code automatically looks at all the sentences in your document and divides the total word count by the number of sentences. The macro then displays the average length in a text popup (“Average Words Per Sentence:”):

Sub CountWords()
Dim s As Range
Dim numWords As Integer
Dim numSentences As Integer
numSentences = 0
numWords = 0
For Each s In ActiveDocument.Sentences
numSentences = numSentences + 1
numWords = numWords + s.Words.Count
Next
MsgBox "Average Words Per Sentence: " + Str(Int(numWords / numSentences))
End Sub

Word Macro Example: Correcting Transposed Letters

Anyone who regularly types texts on a computer will know just how quickly typos like transposed letters occur. But these errors can be quickly corrected. Using the following macro, you only need to place the marker in front of the erroneous pair of letters. Running the macro via key combination or button then allows the letters to be swapped around automatically:

Sub TransposeCharacters()
Selection.MoveRight Unit:=wdCharacter, Count:=1, Extend:=wdExtend
Selection.Cut
Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.Paste
End Sub

Macro Code for Removing All Hyperlinks

Whenever you include website addresses in your texts, Word will automatically change them into clickable hyperlinks to the corresponding sites. But if you don’t want your document to contain these hyperlinks, you usually have to delete the links individually. The following Word macro example saves you a whole lot of work by automatically removing the first hyperlink found in the document. You can therefore run the macro as often as necessary until all the hyperlinks are gone:

Sub RemoveHyperlinks()
'On Error Resume Next
Dim x As Variant
For Each x In ActiveDocument.Hyperlinks
Selection.WholeStory
Selection.Range.Hyperlinks(1).Delete
Next x
End Sub

Click here for important legal disclaimers.

title description ms.date ms.topic dev_langs helpviewer_keywords author ms.author manager ms.technology ms.workload

Walkthrough: Create your first VSTO Add-in for Word

Create an application-level Add-in for Microsoft Word. This feature is available to the application itself, regardless of which documents are open.

02/02/2017

conceptual

VB

CSharp

application-level add-ins [Office development in Visual Studio], creating your first project

Office development in Visual Studio, creating your first project

add-ins [Office development in Visual Studio], creating your first project

Word [Office development in Visual Studio], creating your first project

John-Hart

johnhart

jmartens

office-development

office

Walkthrough: Create your first VSTO Add-in for Word

[!INCLUDE Visual Studio]
This introductory walkthrough shows you how to create a VSTO Add-in for Microsoft Office Word. The features that you create in this kind of solution are available to the application itself, regardless of which documents are open.

[!INCLUDEappliesto_wdallapp]

This walkthrough illustrates the following tasks:

  • Creating a Word VSTO Add-in project.

  • Writing code that uses the object model of Word to add text to a document when it is saved.

  • Building and running the project to test it.

  • Cleaning up the completed project so that the VSTO Add-in no longer runs automatically on your development computer.

    [!INCLUDEnote_settings_general]

Prerequisites

You need the following components to complete this walkthrough:

  • [!INCLUDEvsto_vsprereq]

  • Microsoft Word

Create the project

To create a new Word VSTO Add-in project in Visual Studio

  1. Start [!INCLUDEvsprvs].

  2. On the File menu, point to New, and then click Project.

  3. In the templates pane, expand Visual C# or Visual Basic, and then expand Office/SharePoint.

  4. Under the expanded Office/SharePoint node, select the Office Add-ins node.

  5. In the list of project templates, select a Word VSTO Add-in project.

  6. In the Name box, type FirstWordAddIn.

  7. Click OK.

    [!INCLUDEvsprvs] creates the FirstWordAddIn project and opens the ThisAddIn code file in the editor.

Write code to add text to the saved document

Next, add code to the ThisAddIn code file. The new code uses the object model of Word to add boilerplate text to each saved document. By default, the ThisAddIn code file contains the following generated code:

  • A partial definition of the ThisAddIn class. This class provides an entry point for your code and provides access to the object model of Word. For more information, see Program VSTO Add-ins. The remainder of the ThisAddIn class is defined in a hidden code file that you should not modify.

  • The ThisAddIn_Startup and ThisAddIn_Shutdown event handlers. These event handlers are called when Word loads and unloads your VSTO Add-in. Use these event handlers to initialize your VSTO Add-in when it is loaded, and to clean up resources used by your VSTO Add-in when it is unloaded. For more information, see Events in Office projects.

To add a paragraph of text to the saved document

  1. In the ThisAddIn code file, add the following code to the ThisAddIn class. The new code defines an event handler for the xref:Microsoft.Office.Interop.Word.ApplicationEvents4_Event.DocumentBeforeSave event, which is raised when a document is saved.

    When the user saves a document, the event handler adds new text at the start of the document.

    C#

    :::code language=»csharp» source=»../vsto/codesnippet/CSharp/FirstWordAddIn/ThisAddIn.cs» id=»Snippet1″:::

    VB

    :::code language=»vb» source=»../vsto/codesnippet/VisualBasic/FirstWordAddIn/ThisAddIn.vb» id=»Snippet1″:::

    [!NOTE]
    This code uses an index value of 1 to access the first paragraph in the xref:Microsoft.Office.Interop.Word._Document.Paragraphs%2A collection. Although Visual Basic and Visual C# use 0-based arrays, the lower array bounds of most collections in the Word object model is 1. For more information, see Write code in Office solutions.

  2. If you are using C#, add the following required code to the ThisAddIn_Startup event handler. This code is used to connect the Application_DocumentBeforeSave event handler with the xref:Microsoft.Office.Interop.Word.ApplicationEvents4_Event.DocumentBeforeSave event.

    :::code language=»csharp» source=»../vsto/codesnippet/CSharp/FirstWordAddIn/ThisAddIn.cs» id=»Snippet2″:::

    To modify the document when it is saved, the previous code examples use the following objects:

  • The Application field of the ThisAddIn class. The Application field returns a xref:Microsoft.Office.Interop.Word.Application object, which represents the current instance of Word.

  • The Doc parameter of the event handler for the xref:Microsoft.Office.Interop.Word.ApplicationEvents4_Event.DocumentBeforeSave event. The Doc parameter is a xref:Microsoft.Office.Interop.Word.Document object, which represents the saved document. For more information, see Word object model overview.

Test the project

To test the project

  1. Press F5 to build and run your project.

    When you build the project, the code is compiled into an assembly that is included in the build output folder for the project. Visual Studio also creates a set of registry entries that enable Word to discover and load the VSTO Add-in, and it configures the security settings on the development computer to enable the VSTO Add-in to run. For more information, see Build Office solutions.

  2. In Word, save the active document.

  3. Verify that the following text is added to the document.

    This text was added by using code.

  4. Close Word.

Clean up the project

When you finish developing a project, remove the VSTO Add-in assembly, registry entries, and security settings from your development computer. Otherwise, the VSTO Add-in will continue to run every time that you open Word on your development computer.

To clean up the completed project on your development computer

  1. In Visual Studio, on the Build menu, click Clean Solution.

Next steps

Now that you have created a basic VSTO Add-in for Word, you can learn more about how to develop VSTO Add-ins from these topics:

  • General programming tasks that you can perform in VSTO Add-ins: Program VSTO Add-ins.

  • Programming tasks that are specific to Word VSTO Add-ins: Word solutions.

  • Using the object model of Word: Word object model overview.

  • Customizing the UI of Word, for example, by adding a custom tab to the Ribbon or creating your own custom task pane: Office UI customization.

  • Building and debugging VSTO Add-ins for Word: Build Office solutions.

  • Deploying VSTO Add-ins for Word: Deploy an Office solution.

See also

  • Office solutions development overview (VSTO)
  • Word solutions
  • Program VSTO Add-ins
  • Word object model overview
  • Office UI customization
  • Build Office solutions
  • Deploy an Office solution
  • Office project templates overview

It’s indeed not an easy task to prepare a funeral program template being at a shocking psychological state of mind. However, it’s quite inevitable. There are certain programs available, though, to make things look easier in this regard. Specifically, these programs don’t make you stress much on your brain. Making a funeral program can be way simpler through these methods. In this context, MS Word would be the most suitable recommendation.

Needless is to say that MS Word is the most popular editor available for creating manual templates. It is perhaps the easiest option one can have as a word processor. Moreover, MS Word provides various templates to be used for creating funeral programs. One can prepare broachers through it and then have those printed. If wished, one may send the same direction over the web as well, through the mail.

Given below is a step-by-step guide for those interested in creating a funeral program using MS Word.

A Step-by-step Approach to Creating a Funeral Program in Word

The first step towards creating a funeral program using MS Word is to select the right template. In this context, the best recommendation would be to use the already available templates on Word.

Follow the Steps to Facilitate the Task talked Above.

  1. Open Microsoft Word, and then put a click on ‘File.’ Next, put a tap on the ‘New’ option. Those uninitiated, this ‘New’ icon moreover looks like a plain paper, one edge (right to be specific) of which is folded.
  2. Upon putting clicks, as mentioned above, it is going to make a pop-up window evident. The user has to select any of these simples. There are various categories available as well; those can be found at the left of the window appearing.
  3. You have to select anything or anyone between ‘Cards,’ ‘Flyers,’ or ‘Brochures.’ After selecting any one of these, you have to pick the type of template you would like to use.
  4. Now it’s time to provide your details and a picture. To do this, you have to put a click on the form or simply on the section provided for the content. You can fix the contents as per your requirements.
  5. Once the contents are prepared, simply save those and put those to be printed. You may take it through a drive as well to have the printout elsewhere.

In Case You Want to Have a Customized Program

Watch our tutorial video

Those who want to customize the program further can go for downloading a template. The good news is that there are downloadable templates available for MS Word explicitly. In fact, there are various sites through which one can download these for free. It is recommended that one should check once whether the template is for MS Word. The advantage of this approach is that editing these templates is super easy.

It’s true that there are funeral templates available that can be edited through external editors as well. However, it is always advised that one should go with the funeral templates that can be attuned with MS Word. These are mostly downloadable; those who are not-so-tech-savvy can also find it a convenient option. One of the biggest advantages of templates compatible with MS Word is that it doesn’t have any constraint in terms of printers. In other words, these can be put for print through any printer.

While Going with Premium Templates

  • Sunrise1

    Sunrise1

    $1.95

  • Flowers7

    Flowers7

    $2.25

  • Flowers6

    Flowers6

    $2.25

  • Flowers4

    Flowers4

    $2.25

  • Flowers3

    Flowers3

    $2.25

  • Flowers2

    Flowers2

    $2.25

  • Butterfly4

    Butterfly4

    $2.25

  • Butterfly3

    Butterfly3

    $2.25

  • Crane1

    Crane1

    $2.25

There are so many options one can find for funeral programs to be printed, available absolutely for free. Also, there are various premium options available; those involve some charges. One may go with those as well. But, on most occasions, these are not compatible with MS Word. Hence, it is important to check compatibility while opting for the premium ones.

To Create DIY Funeral Templates

As discussed above, there are various templates available online through which funeral programs can be made in word. However, there are some people who wish to prepare DIY funeral templates. They basically want to prepare it with greater emotional involvement. It is possible for someone to prepare the template all by own. On most occasions, Adobe Illustrator is recommended for creating such customized templates. Those who want the template to be compatible with MS Word are recommended to go with Microsoft Publisher.

  • Sunrise1

    Sunrise1

    $1.95

  • Seagulls2

    Seagulls2

    $2.25

  • Cross2

    Cross2

    $2.25

  • Lake1

    Lake1

    $2.25

  • Rainbow1

    Rainbow1

    $2.25

  • Sunset2

    Sunset2

    $2.25

  • sky theme funeral program templates

    Sky1

    $2.25

  • Ocean template background

    Ocean1

    $2.25

  • Cross1

    Cross1

    $2.25

At the same time, it is important to have it in mind that there are various sites those charge some amounts for using such DIY templates. Despite offering free-to-download templates, they still charge when someone comes with his own template. They charge even if you downloaded a free template from another source. There would be a lot of hassle in this way. The best recommendation to get things done is always to download a free MS Word compatible template.

Don’t Just Decide to See the Previews

There is no scarcity of freely available templates for creating a funeral program. These can be availed in various dimensions, shapes, and sizes. One may go with any of these. However, it is important to have it in mind that the details desired to be provided fit well within the template you choose. In this context, it is advised not just to have a preview and decide instantly.

It’s seen on most occasions that the shape shown trough preview is not exactly the same after it is downloaded. On many occasions, not every detail can be adjusted within the downloaded format. Hence, it is advised to download the template first and then check to ensure that it can contain every detail within it. This can be tried for websites offering free templates for funeral programs.

As evident, creating a funeral program in MS Word is not a tough task. Having free templates available, things have gone much more convenient these days. However, to avoid any kind of mistake, it is suggested to decide well about the things to be included. Starting from the images of the deceased person to the names of family members, every aspect should be checked well. The thing is, people often forget to add the names of some beloved friends of the deceased person on such occasions. To avoid any sort of flaws, it is highly advised that one must thoroughly check things prior to delving into designing.

Набор возможностей текстового редактора Microsoft Word действительно очень широк. С помощью этой программы можно решать множество задач, которые возникают при работе с текстовыми документами любой направленности, что и делает этот продукт таким популярным. В Word реализована даже небольшая среда для программирования, с помощью которой можно значительно облегчить себе работу. В самом редакторе это называется макрокомандой или, как называют чаще, макросом. К сожалению, многие пользователи избегают знакомства с эти инструментом, ошибочно полагая, что это что-то сложное и не особо нужное. В этой статье подробно рассмотрим, как создать макрос в Word, что это вообще такое и почему вы делали неправильно, не пользуясь макрокомандами. Давайте разбираться. Поехали!

Макросы в Microsoft Word

Что это такое

Макрокоманда — это, по сути, небольшая программа, которая позволяет автоматизировать и облегчить работу с текстом. В большинстве продуктов Microsoft реализована функция, сохраняющая историю действий пользователя, наиболее часто используемые инструменты и прочее. Всё это можно перевести в формат команд, и вместо того, чтобы каждый раз делать одно и то же, вы просто нажмёте клавишу на клавиатуре, и Word всё сделает за вас. Удобно? Ещё бы! На самом деле, это совсем не сложно. Далее в статье по порядку о том, как создать макрос.

Макросы позволяют выполнять несколько основных функций. Они предназначены для реализации следующих задач:

  • Ускоряют часто выполняемые процедуры и операции внутри текстового редактора Word. Это относится к редактированию, форматированию и не только.
  • Объединяют несколько команд в цельное действие «от и до». Как пример, используя макрос, можно простыми движениями моментально вставить таблицу, которая будет иметь определённые заданные размеры, а также получит нужное число столбцов и строк.
  • Упрощают получение доступа к некоторым функциям и инструментам для работы с текстом, графиков и пр. При этом они могут располагаться в разных окнах и разделах программы.
  • Автоматизируют сложные последовательные операции и действия.

Редактор Visual Basic

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

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

Алгоритм действий при создании команды следующий:

  • Определить порядок действий.
  • Выполнить.
  • Записать действия в макрос.

Например, вам нужно выделить жирным шрифтом часть текста в таблице. Для записи команды придётся использовать горячие клавиши — комбинации для каждого инструмента вы можете подсмотреть, наведя курсор на нужный инструмент.

Кнопка «Макросы» Word

Допустим, нужная вторая колонка. Перемещение между столбцами таблицы осуществляется при помощи клавиши «Tab». Вы нажимаете «Tab» необходимое количество раз, пока не дойдёте до нужной колонки. Затем, если вам нужно выделить часть содержимого ячейки, снимаете выделение, нажав стрелку влево. Далее выделим два слова из ячейки. Выполните комбинацию Ctrl+Shift и нажмите стрелку вправо дважды (либо столько раз, сколько слов необходимо выделить). И последний шаг — сделать выделенную область полужирной с помощью комбинации Ctrl+B.

Теперь, определившись с порядком действий, запишите макрокоманду. Для этого, перейдите на вкладку «Вид» и отыщите в панели инструментов кнопку «Макросы». Кликнув по ней, вы увидите маленькое меню, в котором нужно выбрать пункт «Записать макрос». В появившемся окне введите название для команды и нажмите на кнопку «Записать». Сразу после этого, возле курсора появится иконка с кассетой, свидетельствующая о том, что началась запись. Выполните чётко по порядку все необходимые действия (в этом примере для выделения полужирным шрифтом нескольких слов из ячейки таблицы). После того как вы всё сделали, нажмите на значок «Стоп» (квадратик) в нижней части окна программы. Всё, макрос готов.

Как записать макрос

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

Пункт «Запись макроса»

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

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

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

Алгоритм действий можно представить в таком виде:

  • В зависимости от того, какая версия текстового редактора Word используется, откройте вкладку «Разработчик» или «Вид», где располагается кнопка «Макросы». Нужно просто кликнуть по пункту «Запись макроса».
  • У каждого макроса должно быть своё имя. Его можно задать сугубо на собственное усмотрение. Это на его функциональность никак влиять не будет.
  • Если дать макросу точно такое же имя, как и у стандартных макросов в программе Word, он будет выполнять его функции вместо основного. Поэтому не поленитесь заглянуть в меню «Макросы» и открыть раздел «Команды Word». Здесь прописаны все стандартные названия.
  • В строке, которая называется «Макрос доступен для» нужно выбрать, для чего именно он будет доступен.
  • В графу с описанием нужно ввести собственное описание создаваемого макроса.
  • Далее можно кликнуть на «Начните запись», либо же «Создайте кнопку». В первом случае запись макроса начнётся без его привязки к кнопке на панели управления или клавиатуре. Во втором макросу будет задана соответствующая клавиша или кнопка.
  • Добавьте один или несколько документов, куда следует добавить новый макрос. Это делается через «Параметры Word» во вкладке «Панель быстрого доступа».
  • В левом окне выберите нужный макрос для записи и кликните по кнопке «Добавить».
  • Для изменения настроек этой кнопки всегда есть возможность кликнуть на «Изменить».
  • Далее выбирайте символ, который хотите использовать для кнопки.
  • Укажите имя. Именно оно будет затем отображаться в соответствующем поле.
  • Дважды кликните ОК, чтобы начать запись макроса.
  • Когда потребуется остановить запись, жмите соответствующую клавишу в меню «Макросы».

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

Добавление макроса в Word

Запуск записи макроса в Word

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

Новое сочетание клавиш

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

Записанный макрос в дальнейшем можно будет использовать на своё усмотрение.

Использование макросов

Как же всё это использовать? А очень просто: в панели инструментов нажмите кнопку «Макросы» и одноимённый пункт в появившемся меню — перед вами откроется список всех макросов. Выберите сохранённый вами и нажмите «Выполнить». Существует более удобный вариант — создать специальную кнопку в панели инструментов. Делается это следующим образом: перейдите в меню «Файл», затем «Параметры» и кликните по пункту «Панель быстрого доступа». В разделе «Выбрать команды из:» укажите «Макросы» и выберите из них требуемый. После этого кликните по кнопке «Добавить». Также вы можете назначить иконку, которая будет отображаться для этой кнопки. Готово. В ленте инструментов появится соответствующая иконка, нажатием на которую вы запустите записанный вами алгоритм действий.

Открытие макросов в Word

Выбор и запуск макроса в Word

Создать макрокоманду можно практически для чего угодно. Можно изменять абзацный отступ, межстрочные интервалы, выровнять области текста, выполнить расчёт заданных значений, или настроить автоматическое заполнение таблицы. Нажмите «Записать макрос» и кликайте мышкой, вызывая соответствующие меню и задавая необходимые значения. Только не выделяйте текст мышкой, для этого лучше использовать горячие клавиши или специальный инструмент программы. Как только всё будет сделано, остановите запись.

Подобные команды могут содержать любое количество шагов и быть любого уровня сложности. Процесс создания макрокоманд одинаковый и для Word 2007, и для Word 2010, и для версии Word 2013.

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

Понравилась статья? Поделить с друзьями:
  • Create pivot table in excel
  • Create pdf with microsoft word
  • Create pdf from excel file
  • Create pdf for word
  • Create paragraph in word