What can vba do in word

VBA is a form of Visual Basic, which is an old programming language developed by Microsoft. Although it’s not popular in global programming, it’s a common language in macros including those created in Microsoft Word.

Opening the VBA Workspace

We showed you how to open macro windows, but we’ll reiterate how to open a macro window again. Macro tools are found in the «View» ribbon tab. This tab has several layout views that you can use such as the way it looks as you type a document or the print view, but in the far-right side of the tab you can see a «Macros» category. This category contains the button named «Macros.»

(Macros button dropdown options)

Click the «Macros» button and you see two available options. (The «Pause Recording» option is when you record a simple macro, but it’s only enabled when you are actually recording a macro and grayed out when it’s not a viable option.) Click the «View Macros» option to open a window that displays a list of currently recorded and saved macros.

(View a list of stored macros)

The window prompts you to name a new macro or choose one from the list to edit it. In the image above, no macros are saved, so you can only create a new one. Type a macro name into the text box and then click the «Create» button. This button will open the VBA interface where you can create a macro based on the VBA language.

The VBA Macro Interface

When you click the «Create» button, a new window opens, which is very different from the Microsoft Word interface. This interface is the VBA window that looks the same throughout any Office product. Should you decide to create a macro in Excel, for instance, the VBA window will look the same as it looks in Microsoft Word.

The window has several important sections as you create your macro.

(VBA interface)

The main center area is where you type your VBA code. A subroutine (discussed later) is created based on the macro name that you enter. As you can see in the image above, the subroutine «test» was created, because the name given to the macro was «test.»

In the left panel, the project is shown with a few subdirectories. The VBA interface is set up to provide a hierarchy of objects in your document. The main hierarchy is the project file. Within this file is the «document» object. This document is given the default name «ThisDocument» in a VBA project.

The «Modules» directory contains the files that contain your VBA code. Modules can be organized into different files, but the VBA interface automatically creates a new module file called «NewMacros.» You can change this file name, but it’s recommended for simple macros that you should leave it with the original file name. Once you better understand how to create module files that interact with each other, then you can create different file names and change the defaults to one of your own.

Anatomy of a Subroutine

VBA components are written in subroutines. Subroutines are small functions that perform an action when you call it from your Word document. These functions are the foundation for your macros. You can have one function that controls all of the commands for your macro, or you can split your macro into several functions in your Module file. The examples in this chapter use just one subroutine, but just know that you can create several to work with a macro.

All subroutines start with the keyword «Sub» in a file. When you see this word, you know that you have a subroutine. Any word following the subroutine keyword is the name. In this example (shown in the image above), the subroutine’s name is «test.» Remember that the subroutine’s name is set to the name you enter in the macro configuration window in Word, but you can always change this name later.

Subroutines are ended using the statement «End Sub,» which always terminates any statements contained within the subroutine structure. The «Sub» command starts the subroutine, and the «End Sub» statement ends it. Any content within these two statements compose the subroutine and will be executed when you call a macro.

Creating Your First Macro

Any statements created in a subroutine will run when you execute a macro. The VBA language has several functions and statements that you need to learn. Learning a language syntax is easy once you understand one language. The VBA language is easier than most, because it’s closest to the standard English language. To learn how to create a macro, you must learn how to create simple ones until you increase your knowledge of the language slowly as you set up more subroutines and statements. Just a simple macro that displays a message box is one way to understand the way a macro executes.

For this example’s macro, we’ll create a simple popup box that will display the message «Hello World.» Message boxes are common with macro, VBA an any language. They display a message to the user, and it’s one of the simplest ways to illustrate the way a language and framework works for a developer.

The «MsgBox» function is what can be used to display a message to the user. You follow this keyword name with a message enclosed in quotes. If you don’t use proper syntax, VBA will return an error message and the macro will not execute. Always test your macros before you distribute them. A macro that returns an error might always get halfway through each procedure and find an error. If this happens, you could have corrupted data where one half of the macro executed but the other half stopped due to a run-time error.

Type the following in the «test» subroutine created earlier:

MsgBox «Hello World»

Your VBA interface window should look like the following:

(Hello World example)

You can test your new subroutine by clicking the «Run» button in the main VBA menu.

The «Run» button looks like a play button, and the pause and stop buttons works when you need to control the execution of your subroutine.

Add a Macro Button

Your macro is set, but you need a way to invoke it. You can create a button that will trigger the macro function using the «Developer» ribbon tab. This tab is not enabled by default. You must add it to your interface. Click the «File» ribbon tab and then click «Options.» A window opens where you can enable the tab. The image below shows the section of the window where it can be enabled. Click the «Developer» check box to enable it and click «OK.»

(Enable the «Developer» tab)

After the «Developer» tab is enabled, click it and look at the «Controls» category where many form controls that you recognize can be found.

(Form controls)

Click the «Button» option and a button is created on the page. Double click the button and a new event is created. Type the code below to display a message box:

MsgBox «Hello World»

At this point, a message box is linked with the button. Close the VBA interface and click the button. A message box appears that displays «Hello World.» You’ve officially created your first VBA macro in Word.

When you have a repetitive series of tasks to perform, you can record those tasks as a macro.

  1. Place the cursor where you want to start recording the macro.
  2. Click the Record Macro button.
  3. Give the macro a name.
  4. Click the Keyboard button.
  5. Press the keyboard shortcut keys that you want to use.
  6. Click Assign.
  7. Click Close.

Contents

  • 1 How do you create a macro in Word?
  • 2 How do I add a macro to text in Word?
  • 3 How do I create a macro for text?
  • 4 How do I create a VBA in Word?
  • 5 How do I use VBA in Word?
  • 6 How do I assign a macro to a shape in Word?
  • 7 What is macro text?
  • 8 What is macro key in keyboard?
  • 9 What can VBA do in Word?
  • 10 How do I setup a macro?
  • 11 How do I create a macro in Word 2007?
  • 12 How do you use macros?
  • 13 Where is record macro in Word?
  • 14 Where are macros stored in Word?
  • 15 How do I view macros in Word?
  • 16 How do I start VBA code?
  • 17 How do I use a macro enabled template in Word?
  • 18 How do I create a macro between Excel and Word?
  • 19 How do I open VBA in Word?
  • 20 How do you assign a macro to a shape?

How do you create a macro in Word?

Record a macro with a button

  1. Click View > Macros > Record Macro.
  2. Type a name for the macro.
  3. To use this macro in any new documents you make, be sure the Store macro in box says All Documents (Normal.
  4. To run your macro when you click a button, click Button.
  5. Click the new macro (it’s named something like Normal.

How do I add a macro to text in Word?

Set up, define, and record macros

  1. Step 1: Set up the macro. A.
  2. Step 2: Add a macro button to the Quick Access Toolbar. A.
  3. Step 3: Record the macro. Enter the keystrokes you want the macro to record.
  4. Step 4: Stop recording. When finished, select the View tab again, then click Stop Recording.

How do I create a macro for text?

Create a text macro

  1. Choose Window > Text Macros.
  2. If you want to create a text macro from existing text, select the text in the document.
  3. Choose New Macro from the Text Macros panel menu, or click the New Macro button in the Text Macros panel.
  4. Enter a macro code in the Macro Code text box.

How do I create a VBA in Word?

Steps for Adding a Macro to Word

  1. Go to the View tab, and click on Macros in the Window area.
  2. Name your macro in the Macro name: box.
  3. Click Create.
  4. Close Word’s VBA editor by going to File, Close and Return to Microsoft Word.

How do I use VBA in Word?

Word

  1. On the Developer tab, click Visual Basic. If you don’t see the Developer tab: Click File > Options.
  2. In the Visual Basic Editor, on the Help menu, click Microsoft Visual Basic for Applications Help.
  3. In the Search box, type the method, property, function, statement, or object that you want help with, or type a query.

How do I assign a macro to a shape in Word?

How To: Assign a Macro to a Button or Shape

  1. Tools menu > Macro > Macros, select the Macro, and click Run.
  2. Shortcut Key combo Alt+F8, select the Macro, and click Run.
  3. Run Macro button on the Visual Basic toolbar, select the Macro, and click Run.
  4. Click in the macro with the mouse and press F5.

What is macro text?

A text macro is a command that will produce text, for example a signature block or a frequently used paragraph. Why use text macros? Text macros will enable you to work more efficiently by voice, by producing frequently used phrases and paragraphs with a single command.

What is macro key in keyboard?

A macro key is a key that was featured on various early PC keyboards and has been removed from most keyboards since.A key sequence is a series of keyboard keystrokes, mouse actions, or menu actions that are bound to a command. The macro key can also be used to conveniently launch a program.

What can VBA do in Word?

VBA is the programming language used to automate Microsoft Office programs including Word, Excel, Outlook, PowerPoint, and Access. Macros are blocks of VBA code that perform specific tasks. When you Record a Macro, Word will write VBA code into a Macro, allowing you to repeat your actions.

How do I setup a macro?

How do I create macros?

  1. Using the mouse that you want to configure, start Microsoft Mouse and Keyboard Center.
  2. In the list under the button that you want to reassign, select Macro.
  3. Click Create a new Macro.
  4. In the Name box, type the name of the new macro.
  5. Click in Editor, and enter your macro.

How do I create a macro in Word 2007?

How to Create a Word 2007 Macro

  1. Think about what you’re going to do.
  2. Click the Developer tab on the Ribbon and then click the Record Macro button in the Code group.
  3. Type the name of the macro you want to create in the Macro Name text box.

How do you use macros?

Run a macro from the Developer tab

  1. Open the workbook that contains the macro.
  2. On the Developer tab, in the Code group, click Macros.
  3. In the Macro name box, click the macro that you want to run, and press the Run button.
  4. You also have other choices: Options – Add a shortcut key, or a macro description.

Where is record macro in Word?

Record a Macro in Word – Instructions

  1. To record a macro in Word, click the “View” tab in the Ribbon.
  2. Then click the drop-down part of the “Macros” button in the “Macros” button group.
  3. Then select the “Record Macro…” command from the drop-down menu that appears to open the “Record Macro” dialog box.

Where are macros stored in Word?

Macros are stored either in Documents or Templates. Documents containing macros have a format extension of “. docm” and Templates have a “. dotm” extension.

How do I view macros in Word?

Here’s how you can find macros and VBA modules in your document:

  1. In Word or Excel, click View > Macro > View Macros. In PowerPoint, click View > Macro. In the Macro box, pick the macro you want to remove and click Delete.
  2. Press Alt+F11 to find macros in the VBA Editor.

How do I start VBA code?

Under Developer tab from the main menu, click on “Visual Basic” icon it will open your VBA editor. It will open a VBA editor, from where you can select the Excel sheet where you want to run the code. To open VBA editor double click on the worksheet. It will open a VBA editor on the right-hand side of the folder.

How do I use a macro enabled template in Word?

  1. Start Microsoft Word.
  2. On the File tab, under Help, click Options. The Word Options dialog displays.
  3. Select Trust Center > Trust Center Settings > Macro Settings.
  4. Click Enable all macros (not recommended, potentially dangerous code can run).
  5. Select the Trust access to the VBA project object model check box.

How do I create a macro between Excel and Word?

Create a macro in Microsoft Excel

  1. In the Macros window, type a name for the new macro in the Macro name text field.
  2. Click the Create button.
  3. The Microsoft Visual Basic for Applications program opens, where you can create the macro by typing the Visual Basic code manually.

How do I open VBA in Word?

Open a specific Word document through Excel with VBA code

  1. In Excel workbook, press the Alt + F11 keys to open the Microsoft Visual Basic for Applications window.
  2. In the Microsoft Visual Basic for Applications window, please click Insert > Module.
  3. Press the F5 key or click the Run button to run the code.

How do you assign a macro to a shape?

Here are the steps to assign a macro to a shape in your worksheet:

  1. Click on the Insert tab in the ribbon.
  2. Click on Shapes.
  3. Select a Shape (I used a rounded rectangle)
  4. Click and drag on the worksheet to set the size of the shape.
  5. You can then write some text.
  6. Then, right-click on the Shape and select Assign Macro.

word vba tutorial

Welcome to the Word VBA Tutorial. VBA is a great tool not only to be leveraged in MS Excel. Often it is worth to save some time doing repeatable tasks by adopting some VBA macros in Word or PowerPoint too. Today I wanted to focus a little bit on starting you off in Word VBA macro programming.

vba word tutorialWhen moving to macro programming in Word VBA you will stumble upon issues you would normally not expect in Excel. Lets take the example of moving around the Word file – in Excel you have spreadsheets which are easy to navigate around. In Word, however, you have a lot of different content e.g. text, objects like images and charts, tables etc. Navigating around Word file in VBA is the greatest challenge you will face. Today I would like to focus on that and other frequently used features in Word VBA. So let’s kick off this Word VBA Tutorial.

Starting your journey with programming in Visual Basic for Applications (VBA)? Start with my VBA Tutorial.

Word VBA is identical to Excel VBA – be sure to leverage the VBA Cheat Sheet

VBA Word Navigating

Let’s start with adding content to the most common places the start and end of a Word document in VBA. Know if you Google for this you will get tons of non-sense methods of navigating around Word files. I was truly amazed at how poorly it is documented.

Beginning and End of the Word Document

Go to the Beginning of a Word Document:

'Start - add text to the beginning of the Word Document
Dim startMark As Range
Set startMark = ActiveDocument.Range(0, 0)
startMark.Text = "This is the start of the document"

Go to the End of a Word Document:

'End - add text to the end of the Word Document
Dim endMark As Range
Set endMark = ActiveDocument.Range(Len(ActiveDocument.Range))
endMark.Text = "This is the end of the document"

Finding and replacing text in a Word Document with VBA

Finding and replacing text are basic functions that you will probably need to leverage every now and then.

'Find and print text in MsgBox
Dim selectText As Range
Set selectText = ActiveDocument.Content
selectText.Find.Execute "Hello"
If selectText.Find.Found Then
  MsgBox selectText.Text
End If
'Find and replace all instances of a specific text
Dim replaceText As Range
Set replaceText = ActiveDocument.Content
replaceText.Find.Execute FindText:="Hello", ReplaceWith:="Goodbye", Replace:=wdReplaceAll

VBA Word Text formatting

One of the first things you would want to do is probably text formatting in Word VBA.

Let’s start by adding some text to our document:

'Select the beginning of the document
ActiveDocument.Range(0).Select
'Type "Hello World!"
Selection.TypeText Text:="Hello World!"

Bold & Italic

To change the font weight to bold see below:

'Select the word "Hello"
ActiveDocument.Range(0, 5).Select

'Toggle the bold property
Selection.Font.Bold = wdToggle

To change the text decoration to italic see below:

'Select the word "World"
ActiveDocument.Range(0, 5).Select
'Toggle the bold property
Selection.Font.Bold = wdToggle

Below the final result of the code above:
Word VBA Tutorial: Bold and Italic

Font size and name

Using the “Hello World!” example above we can similarly change the text font name and font size as shown below:

'Change font size
Selection.Font.Size = 20 'Size: 20
Selection.Font.Grow 'Size: 22
Selection.Font.Shrink 'Size: 20
'Change font name to "Aharoni"
Selection.Font.Name = "Aharoni"

VBA Word Tables

When editing Word files you might want to leverage tables as it is much easier to navigate around them in an automated way. My approach is to insert/modify tables in Word without and borders (invisible). This way you can guarantee a consistent and easy to navigate structure in Word. Let’s go through some of the basic functions around tables.

Add a table

Let’s add a table to the beginning of the Word document:

 Dim begin As Range
 Set startMark = ActiveDocument.Range(0, 0)
 'range as Range, NumRows as Long, NumColumns as Long
 Call ActiveDocument.Tables.Add(startMark, 3, 6) 'add to beginning of doc, 3 rows, 6 cols

Edit cell text

'Modify cell (1,3) to "Hello World!"
With ActiveDocument.Tables(1)
        .Cell(1, 3).Range.Text = "Hello World!"
End With

Working on rows and columns

With ActiveDocument.Tables(1)
        ' Modify height of row 1
        .Rows(1).Height = CentimetersToPoints(0.65)
        ' Modify width of column 1
        .Columns(1).Width = CentimetersToPoints(2.54)
        'Merge cell (1,3) with cell (1,4) - cells must be next to each other
        .Cell(1, 3).Merge .Cell(1, 4)
End With

Formatting borders

'Modify row 1 border, single, black and 100pt
 With ActiveDocument.Tables(1).Rows(3).Borders(wdBorderBottom)
        .LineStyle = wdLineStyleSingle
        .LineWidth = wdLineWidth100pt
        .Color = wdColorBlack
End With

In progress…

Содержание

  • VBA PDF (бесплатные загрузки)
  • Примеры Word VBA «Шпаргалка»
  • Учебное пособие по макросам Word VBA
  • Пример простого макроса Word
  • Объект документа Word
  • Документы
  • Диапазон, выделение, абзацы
  • Примеры макросов Word

Добро пожаловать в наше мега-руководство по Word VBA / макросам!

Эта страница содержит:

    1. Учебное пособие по Word VBA в формате PDF (бесплатная загрузка)
    2. Word VBA «Шпаргалка», содержащая список наиболее часто используемых фрагментов кода Word VBA.
    3. Полное руководство по Word VBA / Macro.
    4. Список всех наших руководств по макросам Word VBA с возможностью поиска

Возможно, вас заинтересует наше интерактивное руководство по VBA для Excel. Хотя некоторые из примеров / упражнений относятся к Excel VBA, большая часть содержимого является общим для всех VBA, и вам может быть полезно изучить такие концепции, как If, Loops, MessageBoxes и т. Д.

VBA PDF (бесплатные загрузки)

Загрузите наше бесплатное руководство по Microsoft Word VBA! Или учебники VBA для других программ Office!

Скачать

Ниже вы найдете простые примеры кода VBA для работы с Microsoft Word.

Выбрать / перейти к

ОписаниеКод VBABackspaceSelection.TypeBackspaceВыбрать весь документSelection.HomeKey Unit: = wdStory
Selection.ExtendКопироватьSelection.CopyУдалитьSelection.Delete Unit: = wdCharacter, Count: = 1Вставить послеSelection.InsertAfter «текст»Начало строкиSelection.HomeKey Unit: = wdLineКонец линииSelection.EndKey Unit: = wdLineВставитьSelection.PasteВыбрать всеSelection.WholeStoryВыбрать всю строкуSelection.EndKey Unit: = wdLine, Extend: = wdExtendВверх по абзацуSelection.MoveUp Unit: = wdParagraph, Count: = 1Переместить вправо на один символSelection.MoveRight Unit: = wdCharacter, Count: = 1Переместить вправо на одну ячейку в таблицеSelection.MoveRight Unit: = wdCellПерейти к началу документаSelection.HomeKey Unit: = wdStoryПерейти в конец документаSelection.EndKey Unit: = wdStoryПерейти на страницу 1Selection.GoTo What: = wdGoToPage, Which: = wdGoToNext, Name: = ”1 ″Перейти к началу страницыSelection.GoTo What: = wdGoToBookmark, Name: = ” Page”
Selection.MoveLeft Unit: = wdCharacter, Count: = 1

Return to Top

Закладки

ОписаниеКод VBAДобавлятьС ActiveDocument.Bookmarks
.Add Range: = Selection.Range, Name: = «Name».
.DefaultSorting = wdSortByName
.ShowHidden = Ложь
Конец сСчитатьDim n as Integer
n = ActiveDocument.Bookmarks.CountУдалитьActiveDocument.Bookmarks («Имя закладки»). УдалитьСуществуют?Если ActiveDocument.Bookmarks.Exists («BookmarkName») = True, то
‘Сделай что-нибудь
Конец, еслиПерейти кSelection.GoTo What: = wdGoToBookmark, Name: = ”BookmarkName”ВыбиратьActiveDocument.Bookmarks («Имя закладки»). ВыберитеЗаменить текстSelection.GoTo What: = wdGoToBookmark, Name: = ”BookmarkName”
Selection.Delete Unit: = wdCharacter, Count: = 1
Selection.InsertAfter «Новый текст»
ActiveDocument.Bookmarks.Add Range: = Selection.Range, _
Name: = ”BookmarkName”

Return to Top

Документ

ОписаниеКод VBAАктивироватьДокументы («Example.doc»). АктивироватьДобавить в переменнуюDim doc As Document
Установить doc = Documents.AddДобавлятьDocuments.AddДобавить (из другого документа)Documents.Add Template: = ”C: Forms FormDoc.doc”, _
NewTemplate: = FalseЗакрыватьДокументы («Example.doc»). ЗакрытьЗакрыть — сохранить измененияДокументы («Example.doc»). Закройте SaveChanges: = wdSaveChangesЗакрыть — не сохранятьДокументы («Example.doc»). Закройте SaveChanges: = wdDoNotSaveChanges.Закрыть — запрос на сохранениеДокументы («Example.doc»). Закройте SaveChanges: = wdPromptToSaveChanges.

Return to Top

Столбцы

ОписаниеКод VBAСохранить какДокументы («Example.doc»). SaveAs («C: Example Example.doc»)СохранитьДокументы («Example.doc»). СохранитьЗащищатьДокументы («Example.doc»). Защитить пароль: = «пароль»Снять защитуДокументы («Example.doc»). Снять пароль: = «пароль»Число страницDim varNumberPages как вариант
varNumberPages = _
ActiveDocument.Content.Information (wdActiveEndAdjustedPageNumber)РаспечататьДокументы («Example.doc»). Распечатать

Return to Top

Устали искать примеры кода VBA? Попробуйте AutoMacro!

Шрифт

ОписаниеКод VBAРазмерSelection.Font.Size = 12ЖирныйSelection.Font.Bold = TrueКурсивSelection.Font.Italic = TrueПодчеркиваниеSelection.Font.Underline = wdUnderlineSingleВсе заглавные буквыSelection.Font.AllCaps = TrueЦветSelection.Font.TextColor = vbRedИмяSelection.Font.Name = «Абади»Нижний индексSelection.Font.Subscript = TrueSuperScriptSelection.Font.Superscript = TrueЦвет выделенияSelection.Range.HighlightColorIndex = wdYellowСтильSelection.Style = ActiveDocument.Styles («Нормальный»)

Return to Top

Вставлять

ОписаниеКод VBAВставить автотекстSelection.TypeText Текст: = ”a3 ″
Selection.Range.InsertAutoTextВставить код датыВставить файлSelection.InsertFile («C: Docs Something.doc»)Вставить разрыв страницыSelection.InsertBreak Тип: = wdPageBreakВставить символ абзацаSelection.TypeText Text: = Chr $ (182)Вставить вкладкуSelection.TypeText Текст: = vbTabВставить текстSelection.TypeText Text: = «Любой текст»Вставить абзац типаSelection.TypeParagraphВставить абзацSelection.InsertParagraph

Return to Top

Петли

ОписаниеКод VBAСделать до конца документаСделать до ActiveDocument.Bookmarks (« Sel») = ActiveDocument.Bookmarks (« EndOfDoc»)
‘Сделай что-нибудь
SubДля каждого документа в ДокументахDim doc As Document
Для каждого документа в документах
‘Сделай что-нибудь
Следующий документЦикл по абзацамПодпункты через абзацы
Dim i As Long, iParCount As Long
iParCount = ActiveDocument.Paragraphs.CountFori = 1 На iParCount
ActiveDocument.Paragraphs (i) .Alignment = wdAlignParagraphLeft
Далее я

Return to Top

Пункт

ОписаниеКод VBAKeepLinesTogetherSelection.ParagraphFormat.KeepTogether = TrueKeepWithNextSelection.ParagraphFormat.KeepWithNext = ИстинаПробел послеSelection.ParagraphFormat.SpaceAfter = 12Пространство доSelection.ParagraphFormat.SpaceBefore = 0Выровнять по центруSelection.ParagraphFormat.Alignment = wdAlignParagraphCenterВыровнять по правому краюSelection.ParagraphFormat.Alignment = wdAlignParagraphRightВыровнять по левому краюSelection.ParagraphFormat.Alignment = wdAlignParagraphLeftЛевый отступSelection.ParagraphFormat.LeftIndent = InchesToPoints (3,75)Правый отступSelection.ParagraphFormat.RightIndent = InchesToPoints (1)Межстрочный интервалС Selection.ParagraphFormat
.LineSpacingRule = wdLineSpaceExactly
.LineSpacing = 12
Конец сПеребрать все абзацыПодпункты через абзацы
Dim i As Long, iParCount As Long
iParCount = ActiveDocument.Paragraphs.CountFori = 1 На iParCount
ActiveDocument.Paragraphs (i) .Alignment = wdAlignParagraphLeft
Далее я

Return to Top

Учебное пособие по макросам Word VBA

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

Примечание. Если вы новичок в Macros / VBA, вам также может быть полезна эта статья: Как писать макросы VBA с нуля.

VBA — это язык программирования, используемый для автоматизации программ Microsoft Office, включая Word, Excel, Outlook, PowerPoint и Access.

Макросы представляют собой блоки кода VBA, которые выполняют определенные задачи.

Когда ты Записать макрос, Word запишет код VBA в макрос, что позволит вам повторять ваши действия. Вы можете увидеть список всех доступных макросов из Просмотр> Макросы.

После записи макроса вы сможете редактировать макрос из списка макросов:

Когда вы нажимаете Редактировать, вы открываете Редактор VBA. Используя редактор VBA, вы можете редактировать записанные макросы или писать макрос Word с нуля. Для доступа к редактору VBA используйте ярлык ALT + F11 или щелкните Visual Basic от Лента разработчика.

Пример простого макроса Word

Это простой пример макроса Word VBA. Он выполняет следующие задачи:

  • Открывает документ Word
  • Записывает в документ
  • Закрывает и сохраняет документ Word.
123456789101112131415 Sub WordMacroExample ()’Открыть документ и назначить переменнойDim oDoc как документУстановите oDoc = Documents.Open («c: Users something NewDocument.docx»).’Написать в документSelection.TypeText «www.automateexcel.com»Selection.TypeParagraph’Сохранить и закрыть документoDoc.SaveoDoc.CloseКонец подписки

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

Весь код VBA должен храниться в подобных процедурах. Чтобы создать процедуру в VBA, введите «Sub WordMacroExample» (где «WordMacroExample» — желаемое имя макроса) и нажмите ВХОДИТЬ. VBA автоматически добавит круглые скобки и End Sub.

Объект документа Word

При взаимодействии с Microsoft Word в VBA вы часто будете ссылаться на Word «Объекты». Наиболее распространенные объекты:

Объект приложения — сам Microsoft Word

Объект документа — документ Word

Объект диапазона — Часть документа Word

Объект выделения — Выбранный диапазон или положение курсора.

заявка

Приложение — это объект «верхнего уровня». Через него можно получить доступ ко всем остальным объектам Word.

Помимо доступа к другим объектам Word, можно применить настройки «уровня приложения»:

1 Application.Options.AllowDragAndDrop = True

Это пример доступа к «Выборке» в «Windows (1)» в Приложении:

1 Application.Windows (1) .Selection.Characters.Count

Однако к наиболее распространенным объектам Word можно получить доступ напрямую, без ввода полной иерархии. Поэтому вместо этого вы можете (и должны) просто ввести:

1 Selection.Characters.Count

Документы

ActiveDocument

Часто у вас есть два или более документов, открытых в Word, и вам нужно указать, с каким конкретным документом Word следует взаимодействовать. Один из способов указать, какой документ использовать ActiveDocument. Например:

1 ActiveDocument.PrintOut

… Напечатал бы ActiveDocument. ActiveDocument — это документ в Word, который «имеет фокус»

Чтобы переключить ActiveDocument, используйте команду Activate:

1 Документы («Example.docx»). Активировать

Этот документ

Вместо использования ActiveDocument для ссылки на активный документ вы можете использовать ThisDocument для ссылки на документ, в котором хранится макрос. Этот документ никогда не изменится.

Переменные документа

Однако для более сложных макросов может быть сложно отслеживать активный документ. Также может быть неприятно переключаться между документами.

Вместо этого вы можете использовать переменные документа.

Этот макрос назначит ActiveDocument переменной, а затем распечатает документ, используя переменную:

12345 Sub VarExample ()Dim oDoc как документУстановите oDoc = ActiveDocumentoDoc.PrintOutКонец подписки

Документ Методы

Открыть документ

Чтобы открыть документ Word:

1 Documents.Open «c: Users SomeOne Desktop Test PM.docx»

Мы рекомендуем всегда назначать документ переменной при его открытии:

12 Dim oDoc как документУстановите oDoc = Documents.Open («c: Users SomeOne Desktop Test PM.docx»).

Создать новый документ

Чтобы создать новый документ Word:

Мы можем указать Word создать новый документ на основе некоторого шаблона:

1 Documents.Add Template: = «C: Program Files Microsoft Office Templates MyTemplate.dotx»

Как всегда, присвоение документа переменной при создании или открытии помогает избавить от серьезных проблем:

12 Dim oDoc как документУстановите oDoc = Documents.Add (Template: = «C: Program Files Microsoft Office Templates MyTemplate.dotx»)

Сохранить документ

Чтобы сохранить документ:

или Сохранить как:

1 ActiveDocument.SaveAs FileName: = c: Users SomeOne Desktop test2.docx «, FileFormat: = wdFormatDocument

Закрыть документ

Чтобы закрыть документ и сохранить изменения:

1 ActiveDocument.Close wdSaveChanges

или без сохранения изменений:

1 ActiveDocument.Close wdDoNotSaveChanges

Распечатать документ

Это напечатает активный документ:

1 ActiveDocument.PrintOut

Диапазон, выделение, абзацы

Диапазон а также Выбор являются, вероятно, наиболее важными объектами в Word VBA и, безусловно, наиболее часто используемыми.

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

Выбор относится к выделенному тексту (или другому объекту, например изображениям) или, если ничего не выделено, к точке вставки.

Абзацы представляют абзацы в документе. Это менее важно, чем кажется, потому что у вас нет прямого доступа к тексту абзаца (вам нужно получить доступ к определенному диапазону абзацев, чтобы внести изменения).

Диапазон

Диапазон может быть любой частью документа, включая весь документ:

12 Dim oRange As RangeУстановите oRange = ActiveDocument.Content

или он может быть маленьким, как один символ.

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

12 Dim oRange As RangeУстановите oRange = ActiveDocument.Range.Words (1)

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

В следующем примере мы выделим первое слово второго абзаца жирным шрифтом:

123 Dim oRange As RangeУстановите oRange = ActiveDocument.Paragraphs (2) .Range.Words (1)oRange.Bold = True

Установить текст диапазона

Чтобы установить текстовое значение диапазона:

123 Dim oRange As RangeУстановите oRange = ActiveDocument.Paragraphs (2) .Range.Words (1)oRange.Text = «Привет»

(Совет: обратите внимание на пробел после «Hello». Поскольку слово «объект» включает пробел после слова, просто «hello» мы получим «Hellonext word»)

С диапазонами можно делать сотни вещей. Всего несколько примеров (предполагается, что вы уже сделали объектную переменную апельсин относится к интересующему диапазону):

Изменить шрифт

1 oRange.Font.Name = «Arial»

Отображение в окне сообщения количества символов в определенном диапазоне

1 MsgBox oRange.Characters.Count

Вставьте текст перед ним

1 oRange.InsertBefore «это вставленный текст»

Добавить сноску к диапазону

12 ActiveDocument.Footnotes.Add Диапазон: = oRange, _Text: = «Подробнее читайте на easyexcel.net.»

Скопируйте в буфер обмена

1234 oRange.CopyЧасто вам нужно перейти к конкретному диапазону. Итак, вы можете начать, начать и закончитьoRange.Start = 5oRange.End = 50

После приведенного выше кода oRange будет относиться к тексту, начинающемуся с пятого и заканчивающемуся 50-м символом в документе.

Выбор

Выбор используется даже шире, чем Диапазон, потому что с ним легче работать Выборы чем Диапазоны, ЕСЛИ ваш макрос взаимодействует ТОЛЬКО с ActiveDocument.

Сначала выберите желаемую часть вашего документа. Например, выберите второй абзац в активном документе:

1 ActiveDocument.Paragraphs (2) .Range.Select

Затем вы можете использовать объект выбора для ввода текста:

1 Selection.TypeText «Какой-то текст»

Мы можем ввести несколько абзацев ниже «Некоторый текст»:

12 Selection.TypeText «Какой-то текст»Selection.TypeParagraph

Часто необходимо знать, выделен ли какой-то текст или у нас есть только точка вставки:

12345 Если Selection.Type wdSelectionIP ТогдаSelection.Font.Bold = TrueЕщеMsgBox «Вам нужно выделить текст».Конец, если

При работе с объектом Selection мы хотим поместить точку вставки в определенное место и запускать команды, начиная с этой точки.

Начало документа:

1 Selection.HomeKey Unit: = wdStory, Extend: = wdMove

Начало текущей строки:

1 Selection.HomeKey Unit: = wdLine, Extend: = wdMove

Параметр Extend wdMove перемещает точку вставки. Вместо этого вы можете использовать wdExtend, который выделит весь текст между текущей точкой вставки.

1 Selection.HomeKey Unit: = wdLine, Extend: = wdExtend

Переместить выделение

Самый полезный метод изменения положения точки вставки — «Перемещение». Чтобы переместить выделение на два символа вперед:

1 Selection.Move Unit: = wdCharacter, Count: = 2

чтобы переместить его назад, используйте отрицательное число для параметра Count:

1 Selection.Move Unit: = wdCharacter, Count: = — 2

Параметр единицы измерения может быть wdCharacter, wdWord, wdLine или другим (используйте справку Word VBA, чтобы увидеть другие).

Чтобы вместо этого переместить слова:

1 Selection.Move unit: = wdWord, Count: = 2

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

Если вам нужно какое-то свойство или метод, недоступный в объекте Selection, вы всегда можете легко получить диапазон, связанный с выбором:

1 Установите oRange = Selection.Range.

СОВЕТ: Использование Выбор часто проще, чем использование диапазонов, но также и медленнее (важно, когда вы имеете дело с большими документами)

Абзацы

Вы не можете напрямую использовать объект Paragraphs для изменения текста:

1 ActiveDocument.Paragraphs (1) .Text = «Нет, это не сработает»

Выше не сработает (на самом деле выдаст ошибку). Вам нужно сначала получить диапазон, связанный с конкретным абзацем:

1 ActiveDocument.Paragraphs (1) .Range.Text = «Теперь работает :)»

Но вы можете напрямую изменить его стиль:

1 ActiveDocument.Paragraphs (1) .Style = «Нормальный»

или измените форматирование на уровне абзаца:

1 ActiveDocument.Paragraphs (1) .LeftIndent = 10

или, может быть, вы хотите сохранить этот абзац на одной строке со следующим абзацем:

1 ActiveDocument.Paragraphs (1) .KeepWithNext = True

Сделайте абзац по центру:

1 ActiveDocument.Paragraphs (1) .Alignment = wdAlignParagraphCenter

ОЧЕНЬ полезно назначить конкретный абзац объектной переменной. Если мы присвоим переменной конкретный абзац, нам не нужно беспокоиться, станет ли первый абзац вторым, потому что мы вставили перед ним один абзац:

12 dim oPara как абзацУстановите oPara = Selection.Paragraphs (1) ‘здесь мы присваиваем первый абзац текущего выделения переменной

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

1234567 Sub ParagraphExample ()Dim oPara как абзацУстановить oPara = ActiveDocument.Paragraphs (1)MsgBox oPara.Range.TextoPara.Range.InsertParagraphBefore ‘Вставить абзацMsgBox oPara.Range.TextКонец подписки

Объект абзаца очень часто используется в циклах:

123456789101112 Sub LoopThroughParagraphs ()Dim oPara как абзацДля каждого параметра в ActiveDocument.Paragraphs«Сделай что-нибудь с этим. Мы просто покажем’текст абзаца, если его стиль — «Заголовок 4″Если oPara.Style = «Заголовок 4», тоMsgBox oPara.Range.TextКонец, еслиДалее oParaКонец подписки

Word VBA Tutorial Заключение

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

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

Примеры макросов Word
Шаблоны
Добавить новые документы
Подсчет слов в выделенном фрагменте
Текстовые поля
Сохранить как PDF
Закладки
Таблицы
Найти, найти и заменить
Открытые документы

Word VBA: часто задаваемые вопросы

Что такое макрос Word?

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

Есть ли в слове VBA?

Да, в Microsoft Word есть редактор VBA. Доступ к нему можно получить, нажав клавиши ALT + F11 или перейдя в раздел «Разработчик»> «Visual Basic».

Как использовать VBA в Word?

1. Откройте редактор VBA (ALT + F11 или Разработчик> Visual Basic).
2. Выберите «Вставить»> «Модуль», чтобы создать модуль кода.
3. Введите «Sub HelloWorld» и нажмите Enter.
4. Между строками «Sub HelloWorld» и «End Sub» введите «MsgBox« Hello World! »
5. Вы создали макрос!
6. Теперь нажмите «F5», чтобы запустить макрос.

Word and Visual Basic for Applications (VBA): Worth the Effort? (Part 1)

Visual Basic for Applications (VBA) is a programming language developed by Microsoft that is included with Word and other Microsoft Office products. It allows you to write small programs (called scripts or macros) to manipulate the functions of Word that are normally accessible through the standard user interface: menus, dialogs, buttons, drop-downs, checkboxes, radio buttons, and so on.

Why is programmatic manipulation of Word functions useful? You can write macros to do repetitive tasks automatically so that you don’t have to manually repeat the task over and over. The process of performing repetitive tasks automatically is sometimes referred to as ‘automation’. Repetitive tasks can include applying styles, reformatting tables, or importing content from other sources. The macros do the work for you, and they do it faster and more accurately.

As illustrated below, in repetitive task scenarios, a little investment in programming effort can lead to big time savings, especially as the size of the task increases.

Time spent on repetitive tasks

What Can You Do with Macros?

The following are some examples of interesting use cases:

  • Applying formats automatically (for example, setting table headings to repeat when a table expands to a new page)
  • Validating formats (for example, checking that a file conforms to your template and reporting any anomalies)
  • Importing/exporting content to and from other applications (for example, taking content from a spreadsheet, importing it into Word, then formatting it automatically)
  • Working with DITA files (Word VBA has a library of functions specifically for this purpose)

These are just some examples. Since you have access to all document components, there is potential to be very creative.

What’s in It for the Writer?

Learning to use VBA has many benefits for a technical writer. With VBA, you can improve efficiency and accuracy by getting the computer to perform many of your mundane tasks. Computers are excellent at repetitive work (such as applying styles) while humans struggle somewhat. We’re not good at robotic work and we typically need something more engaging and challenging. Creating macros fits into this category. Once you get started, it can become infectious and you subconsciously look for new ways to apply your newfound skills.

Also, adding knowledge of a programming language enhances your skills portfolio. You’ll have a higher level of confidence when conversing with a developer audience and you are more likely to engage with them on a more productive level. Even better, by learning the basics of VBA for Word, you automatically acquire knowledge that allows you to write similar code for other Microsoft Office products, such as Excel.

What’s So Special about VBA Anyway?

VBA is compelling for many reasons. First, Word is ubiquitous. No matter where you work, there is a good chance you will have access to Word. By association, any investment in learning VBA can have broad application.

The VBA language is pretty intuitive and the learning curve is less steep than other programming languages. You don’t need to know a lot of technical details and the language is human-readable. In many cases, you can quickly interpret what the code is doing.

The VBA Editor is a fully-featured environment that includes helpful features like IntelliSense, which offers assistance with VBA syntax as you type or on demand. In addition, the VBA Editor has great debugging features, quick access to help, and an object browser.

The VBA Editor

Finally, it is possible in Word to record your actions, then view the VBA code that was generated for those actions. This feature helps new users become familiar with VBA. If you don’t know how to code an action, just record it and view the generated code afterwards. You can learn a huge amount with just this approach.

Is It Difficult to Learn?

If it’s your first experience of a programming language, it may seem difficult at the beginning. However, in many ways VBA is a great starting point:

  • It is perhaps the easiest of all programming languages used in the technical writing domain.
  • It is object-oriented, which may sound daunting, but actually helps understanding. In the case of Word VBA, the objects you work with are familiar: Documents, Paragraphs, Words, Tables, Rows, Columns, Cells, and so on.
  • The VBA Editor provides an environment that makes writing macros much easier.
  • There is an abundance of sample code, demos, and tutorials. Chances are, the task you want to achieve (or something similar) has been done before, and you can leverage existing code. There is also a huge user community with an array of forums, message boards, and experts to help solve problems.

What Are the Stumbling Blocks?

Most inexperienced writers have blinkers on when it comes to all things programming. Terms such as objects, inheritance, and polymorphism just frighten writers to death. Don’t be put off by the jargon. To get started, all you need to do is focus on a few fundamentals. It is not as difficult as you may think!

Programming terminology

Writers think of programming as a very specialized subject. In general, this is true, but there are cases where non-programmers with some basic knowledge can become quite productive and VBA for Word certainly fits that category.

The final stumbling block is that writers often don’t know where to start. In this series, we’ll do just that: show you the basics and point you in the right direction.

Is It Worth the Time Investment?

Every writer’s situation is different, so only you can decide. You may work in a publications group that uses Adobe FrameMaker or other tools, so you may not want to invest time in learning about VBA for Word.

You may never have a requirement to do any scripting or you may simply have no interest in it, and that’s OK too. However, as you broaden your experience in the world of software documentation, gaining some knowledge of programming would be to your advantage. Where better to start than VBA for Word?

In this series, we introduce a few fundamentals to help you get started with VBA and possibly whet your appetite for further knowledge and exploration. If you are new to VBA, have you encountered scenarios where you think VBA could be useful? If you’ve already used VBA, do you have any helpful hints or suggestions for prospective new VBA users? Feel free to share your thoughts.

Понравилась статья? Поделить с друзьями:
  • What do pcs excel at
  • What can microsoft word be used for
  • What do one word text messages mean
  • What can i do with word processor
  • What do one word replies mean