Vba word change the

I’m working on a macro for Word which detects key words in the text while these are typed.
for example, I want that a Table will be added when the user types table or something like that.. very similar to lyx context, but yet nothing like it.

The table example is very simple compare to the ideas I want to implement with this.

I’m looking for an event in VBA that will be triggered whenever the used types something.

There is an event called WindowSelectionChange (Reference: Event — Document Edited) but it triggers only whenever the SELECTION is changed, meaning only when the user selects another area in the document with the mouse cursor, or whenever the user moves with the keyboard arrows in the document, but doesn’t triggers when the user types text (or press Enter, Space, etc…).

This article provides macros and VBA code snippets that may help you if you are going to create Word macros to handle some operations in relation to Track Changes in Word.

You will find detailed information about how track changes works in my how-it-works article on my website wordaddins.com. The macro code below is related to that article.

IMPORTANT: The macro code in this article is made for Word 2013 and newer versions of Word. Some of the code will result in errors if used in Word 2010 and earlier versions due to changes to the Track Changes features that Microsoft introduced in Word 2013.

MACRO – Reset Advanced Track Changes Options to default

The Advanced Track Changes Options dialog box is used to define which types of changes are tracked and how tracked changes appear for the individual user.

You will find detailed information about the Advanced Track Changes Options dialog box, incl. an illustration showing the default settings, in my how-it-works article on my website wordaddins.com.

The macro below reverts the dialog box to the default settings. If you examine the code, you should be able to adjust it to other setting than the default if desired.

Comments in the macro code explain how the code relates to the dialog box.

Sub AdvancedTrackChangesOptions_SetToDefault()
    'Macro created by Lene Fredborg, Aug-2020
    'Works with Word 2013 and newer versions PC/Windows
    'This macro resets all settings in Advanced Track Changes Options to default
    'The code is organized as in the dialog box for easy reference
    
    With Options
        'MARKUP group
        'Insertions
        .InsertedTextMark = wdInsertedTextMarkUnderline
        .InsertedTextColor = wdByAuthor
        'Deletions
        .DeletedTextMark = wdDeletedTextMarkStrikeThrough
        .DeletedTextColor = wdByAuthor
        'Changed lines
        .RevisedLinesMark = wdRevisedLinesMarkOutsideBorder
        'Comments
        .CommentsColor = wdByAuthor
        
        'MOVES group
        'Track moves
        ActiveDocument.TrackMoves = True
        'Moved from
        .MoveFromTextMark = wdMoveFromTextMarkDoubleStrikeThrough
        .MoveFromTextColor = wdGreen
        'Moved to
        .MoveToTextMark = wdMoveToTextMarkDoubleUnderline
        .MoveToTextColor = wdGreen
        
        'TABLE CELL HIGHLIGHTING group
        'Inserted cells
        .InsertedCellColor = wdCellColorLightBlue
        'Deleted cells
        .DeletedCellColor = wdCellColorPink
        'Merged cells
        .MergedCellColor = wdCellColorLightYellow
        'Split cells
        .SplitCellColor = wdCellColorLightOrange
        
        'FORMATTING group
        'Track formatting
        ActiveDocument.TrackFormatting = True
        'Formatting
        .RevisedPropertiesMark = wdRevisedPropertiesMarkNone
        .RevisedPropertiesColor = wdByAuthor
    End With
    
    With ActiveWindow.View
        'BALLOONS group
        'Preferred width
        'Measure in (must be set before setting value)
        .RevisionsBalloonWidthType = wdBalloonWidthPoints
        'set depending on unit of measurement measurement
        If Options.MeasurementUnit = wdCentimeters Then
            .RevisionsBalloonWidth = CentimetersToPoints(9.4)
        Else
            .RevisionsBalloonWidth = InchesToPoints(3.7)
        End If
        'Margin
        .RevisionsBalloonSide = wdRightMargin
        'Show lines connection to text
        .RevisionsBalloonShowConnectingLines = True
    End With
		
    With Options
        'Paper orientation in printing
        .RevisionsBalloonPrintOrientation = wdBalloonPrintOrientationPreserve
    End With
End Sub

VBA code snippets for misc. Track Changes operations

Below, you will find several small VBA code snippets that may help you create your own macros for handling tracked changes.

Macro code – Turn Track Changes on and off

    'Turn on Track Changes
    ActiveDocument.TrackRevisions = True
    
    'Turn off Track Changes
    ActiveDocument.TrackRevisions = False

Macro code – Count number of tracked changes and comments

    Dim lngCount As Long
    
    'Count number of tracked changes
    lngCount = ActiveDocument.Revisions.Count
    
    'Count number of comments
    lngCount = ActiveDocument.Comments.Count

Macro code – Turn on/off Track Moves and Track Formatting in Advanced Track Changes Options

NOTE: Track Moves and Track formatting are document-specific settings that are saved in the document. All other options in the Advanced Track Changes Options dialog box apply to all Word documents. For details, see my comprehensive track changes article.

    'Turn on Track Moves
    ActiveDocument.TrackMoves = True
    
    'Turn off Track Moves
    ActiveDocument.TrackMoves = False
    
    'Turn on Track Formatting
    ActiveDocument.TrackFormatting = True
    
    'Turn off Track Formatting
    ActiveDocument.TrackFormatting = False

Macro code – Set Simple Markup, All Markup, No Markup, or Original

The code snippets below help you set options in the Display for Review menu.

    'Select Display for Review > Simple Markup
    With ActiveWindow.View.RevisionsFilter
        .Markup = wdRevisionsMarkupSimple
        .View = wdRevisionsViewFinal
    End With
    
    'Select Display for Review > All Markup
    With ActiveWindow.View.RevisionsFilter
        .Markup = wdRevisionsMarkupAll
        .View = wdRevisionsViewFinal
    End With
    
    'Select Display for Review > No Markup
    With ActiveWindow.View.RevisionsFilter
        .Markup = wdRevisionsMarkupNone
        .View = wdRevisionsViewFinal
    End With
    
    'Select Display for Review > Original
    With ActiveWindow.View.RevisionsFilter
        .Markup = wdRevisionsMarkupNone
        .View = wdRevisionsViewOriginal
    End With

Macro code – Show the Revision Pane

    'Show Revisions Pane Vertical
    ActiveWindow.View.SplitSpecial = wdPaneRevisionsVert
    
    'Show Revisions Pane Horizontal
    ActiveWindow.View.SplitSpecial = wdPaneRevisionsHoriz

Macro code – Accept and reject tracked changes

    'Accept all tracked changes in the active document
    ActiveDocument.Revisions.AcceptAll
    
    'Reject all tracked changes in the active document
    ActiveDocument.Revisions.RejectAll
    
    'Accept all tracked changes in the selection
    Selection.Range.Revisions.AcceptAll
    
    'Reject all tracked changes in the selection
    Selection.Range.Revisions.RejectAll

Macro code – Display of tracked changes and comments (revisions)

    'Show revisions and comments, i.e. all types of tracked changes and comments
    ActiveWindow.View.ShowRevisionsAndComments = True
    
    'Hide revisions and comments
    ActiveWindow.View.ShowRevisionsAndComments = False
    
    'Show insertions and deletions (without changing comments display)
    ActiveWindow.View.ShowInsertionsAndDeletions = True
    
    'Hide insertions and deletions (without changing comments display)
    ActiveWindow.View.ShowInsertionsAndDeletions = False
    
    'Show comments
    ActiveWindow.View.ShowComments = True
    
    'Hide comments
    ActiveWindow.View.ShowComments = False
    
    'Show formatting changes
    ActiveWindow.View.ShowFormatChanges = True
    
    'Hide formatting changes
    ActiveWindow.View.ShowFormatChanges = False

Macro code – Select options in Show Markup > Balloons

    'Select Show Markup - Balloons - Show Revisions in Balloons
    ActiveWindow.View.MarkupMode = wdBalloonRevisions
    
    'Select Show Markup - Balloons - Show all Revisions Inline
    ActiveWindow.View.MarkupMode = wdInLineRevisions
    
    'Select Show Markup - Balloons - Show Only Comments and Formatting in Balloons
    ActiveWindow.View.MarkupMode = wdMixedRevisions

Macro code – Turn on/off Trust Center settings related to tracked changes and comments

    'Turn on Warn before printing, saving or sending a file
    'that contains tracked changes or comments
    Options.WarnBeforeSavingPrintingSendingMarkup = True
    
    'Turn off "Warn before printing, saving or sending a file
    'that contains tracked changes or comments"
    Options.WarnBeforeSavingPrintingSendingMarkup = False
    
    'Turn on "Make hidden markup visible when opening or saving"
    Options.ShowMarkupOpenSave = True
    
    'Turn off "Make hidden markup visible when opening or saving"
    Options.ShowMarkupOpenSave = False

VBA is a Microsoft script language, mostly used with Excel. And there are reasons for this – mainly, the skills needed to use VBA are easily grasp by those, using Excel on a daily basis. The second reason is that only in Excel the VB Editor gives a possibility to record a macro. Thus, if you want to use VBA in Access, Word, Outlook or any other MS Application, you should know the commands from before and you need some skills, as far as you cannot just record the macro and simply edit it later.

That is why I have decided to give some useful examples for VBA with Word. This is really not popular, because Word is used mainly for writing 🙂 and not for creating business models, but some of the examples may be useful.


The first example of VBA will simply change the font of the Word document to “Times New Roman”. In order to make it fancier, we will ask a question before the change:

ChangeFontQuestion

The code is pretty much straightforward, we get a message box, the result of the message box is assigned to a variable “intResult”, and if this result is “6”, we change the font. In VBA, “6” is the value, generated from the “Yes” button:

IntResult

So, the code looks like this:

Sub ChangeFont()

    Dim intResult       As Integer

    Dim strMessage      As String

    Dim myRange         As Range

    strMessage = «Do you want to change the font with ««Times New Roman»«?»

    intResult = MsgBox(strMessage, vbYesNo + vbDefaultButton2, «Change Font»)

    If intResult = vbYes Then

       Set myRange = ActiveDocument.Paragraphs(1).Range

       myRange.WholeStory

       myRange.Font.Name = «Times New Roman»

    End If

End Sub

Pretty much, the code may seem a little useless, because the same result can be achieved if you simply select the whole text in Word and change the font. No VBA, nothing. Anyway, this is a good code for reference, if you need to select all text in Word (and Word does not have macro recorder).


In the second example, we will add automatically some text at the beginning and the end of the document. The text added will be hard coded, for easier understanding of the example. Pretty much, the logic is as in the previous example, we simply ask with a message box and if the answer is VbYes, we add some text at the beginning and at the end:

Sub ChangeBeginningAndEnd()

    Dim intResult       As Integer

    Dim strMessage      As String

    Dim rng             As Word.Range

    strMessage = «Should we add something to the beginning and the end of the document?»

    intResult = MsgBox(strMessage, vbYesNo + vbDefaultButton2, _

                         «Change Starting and Ending»)

    If intResult = vbYes Then

       Set rng = ActiveDocument.Range(Start:=0, End:=0)

       rng.Text = «VitoshAcademy.com» & vbCr

       Set rng = ActiveDocument.Range

       rng.EndOf wdStory, wdMove

       rng.Text = «www.facebook.com/vitoshacademy» & vbCr & «www.youtube.com/user/vitoshacademy»

    End If

End Sub


Finally, the last example is something useful – it changes all font with some size to another size. Thus, imagine that you are writing a master thesis of 60 pages, and suddenly you decided to change the size of font from 9 to 10. You cannot go and select all, because there are other fonts. Thus, you need to use a macro! 🙂 :

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

Sub ChangeFontSize()

    Dim intResult       As Integer

    Dim strMessage      As String

    strMessage = «Do you want to change all Fonts with size 9 to size 10?»

    intResult = MsgBox(strMessage, vbYesNo + vbDefaultButton2, «Change Fonts»)

    If intResult = vbYes Then

       Selection.HomeKey unit:=wdStory

       With Selection.Find

          .ClearFormatting

          .Font.Size = 9

          .Text = «»

          .Forward = True

          .Wrap = wdFindContinue

          .Format = True

          .MatchCase = False

          .MatchWholeWord = False

          .MatchWildcards = False

          .MatchSoundsLike = False

          .MatchAllWordForms = False

          Do Until .Execute = False

             With Selection

                .Font.Size = 10

                .Collapse

             End With

          Loop

       End With

    End If

End Sub

The macro here makes a search in the text for font with size 9 and sets it to size 10. The trick is in the usage of a loop in a “With… End With” structure. The trick of the finding is in the clearing of the format.


Pretty much, that is all. If you want to test the macros, you may download the files from here.

12.4. Точная замена

12-04-Точная замена.docm — пример к п. 12.4.

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

12.4.1. Условие

Написать программу на VBA, которая позволяла бы автоматизировать процесс замены одних комбинаций символов другими. В частности, предусмотреть выбор среди следующих объектов замены: заменить букву е на ё, удалить двойные пробелы, заменить обычное тире на длинное. Предусмотреть возможность задавать один из объектов пользователем.

12.4.2. Решение

Создадим пользовательскую форму (рис. 12.1.).

Форма для настройки замены символов

Рис.
12.1.
Форма для настройки замены символов

Основные элементы управления, которые мы используем, это следующие флажки (табл. 12.1.).

Таблица
12.1.
Основные элементы управления

Имя элемента управления Подпись
chk_Space Заменить двойные пробелы на одинарные
chk_Yo Заменить букву е на ё
chk_LongDash Заменить обычные тире на длинные
chk_User Пользовательская замена
cmd_OK ОК

Если выбран флажок chk_User — активируются два текстовых поля ( txt_One и txt_Two ). Их свойства Enabled первоначально установлены в False, при выборе флажка оно устанавливается в True, при снятии — обратно в False. В поле txt_One пользователь может записать последовательность символов, которую нужно заменить на последовательность, которую он может ввести в txt_Two.

Ниже приведен код пользовательских процедур и обработчиков событий элементов управления, которые реализуют вышеописанную функциональность. Листинг 12.4. содержит код обработки события Change для chk_User.Листинг 12.5. представляет собой код, который выполняется при нажатии на кнопку ОК, которая запускает процесс замен. Листинг 12.6. содержит код процедуры, которая вызывает стандартное средство для замены.

Private Sub chk_User_Change()
'Выполняется при изменении состояния
'флажка chk_User
    If chk_User = True Then
    'Если флажок установлен     'активировать поля
        txt_One.Enabled = True
        txt_Two.Enabled = True
    Else
    'Если флажок снят     'заблокировать поля
        txt_One.Enabled = False
        txt_Two.Enabled = False
    End If
End Sub


Листинг
12.4.
Обработка события Change для chk_User

Private Sub cmd_Ok_Click()
'Обработчик нажатия кнопки
'Проверяем, установлен ли каждый
'из флажков и в зависимости от этого
'выполняем вызов пользовательской процедуры
'которая содержит код вызова средства
'Найти и заменить
    If chk_Space = True Then
        Call ReplaceThis("  ", " ")
    End If
    If chk_Yo = True Then
        Call ReplaceThis("е", "е")
    End If
    If chk_LongDash = True Then
        Call ReplaceThis("-", "-")
    End If
    If chk_User = True Then
        Call ReplaceThis(txt_One, txt_Two)
    End If
End Sub


Листинг
12.5.
Обработка события нажатия на кнопку cmd_OK

Public Sub ReplaceThis(str_1, str_2 As String)
'Пользовательская процедура
'Принимает два параметра
'str_1 - это символ, который надо заменить
'str_2 - символ, на который надо заменить
    'Поиск и замена во всем документе
    ActiveDocument.Content. _
    Find.Execute _
    FindText:=str_1, ReplaceWith:=str_2, _
    Replace:=wdReplaceAll
End Sub


Листинг
12.6.
Процедура вызова стандартного средства поиска и замены символов

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

12.5. Проверка правильности создания документа

12-05-Проверка правильности.docm — пример к п. 12.5.

Этот пример будет посвящен использованию стилей при программной обработке документов. Стиль — это набор правил форматирования документа, имеющий имя.

12.5.1. Условие

Предположим, что в нашем документе используется стиль с именем PicLink для форматирования ссылки на изображение в тексте, и стиль PicName — для самого имени изображения. Изображение должно следовать в документе сразу после его упоминания в тексте. Нужно написать программу, которая проверяет номера изображений, упомянутых в тексте и номера иллюстраций и составляет после проверки отчет о соответствии ссылок на иллюстрации их реальным номерам. Для нумерования иллюстраций используется конструкция такого вида: «Рис. X».

12.5.2. Решение

Для начала создадим два стиля. Один назовем PicLink, второй — PicName. Для создания стиля отформатируйте какой-нибудь участок документа так, как нужно, после чего выделите его, щелкните по выделению правой кнопкой мыши и выберите в появившемся меню пункт Стили o Сохранить выделенный фрагмент как новый экспресс-стиль. Появится окно для настройки свойств стиля, разверните его кнопкой Изменить (рис. 12.2.). Задайте имя стиля, место сохранения, в поле Стиль выберите Знака, и нажмите кнопку OK.

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

'Для хранения ссылки на символ
    Dim obj_Char As Range
    'Для хранения текста ссылки на
    'изображение
    Dim str_PicLink As String
    'Для хранения текста названия
    'изображения
    Dim str_PicName As String
    'Для хранения текста отчета
    Dim str_ResultText
    'Счетчик иллюстраций
    Dim num_Counter
    'Ссылка на документ с отчетом
    Dim obj_Doc As Document
    'Для каждого символа в документе
    For Each obj_Char In ActiveDocument.Characters
        'Если стиль символа - PicLink
        'и символ является цифрой, точкой или
        'косой чертой - добавляем символ
        'в переменную
        If obj_Char.Style = "PicLink" Then
            If Asc(obj_Char.Text) >= 46 And _
                Asc(obj_Char.Text) <= 57 Then
                    str_PicLink = str_PicLink + _
                    obj_Char.Text
            End If
        End If
        'Аналогично - для стиля PicName
        If obj_Char.Style = "PicName" Then
            If Asc(obj_Char.Text) >= 46 And _
                Asc(obj_Char.Text) <= 57 Then
                    str_PicName = str_PicName + _
                    obj_Char.Text
            End If
        End If
        'Если стиль - не PicLink и не PicName
        'и переменные, хранящие симолы, взятые
        'из ссылки на рисунок и названия, не
        'пусты - проверяем, одинаковы ли эти
        'символы и формируем строку для
        'последующего вывода в файл отчета
        If obj_Char.Style <> "PicLink" And _
            obj_Char.Style <> "PicName" And _
            Len(str_PicLink) > 0 And _
            Len(str_PicName) > 0 Then
                'Увеличим на 1 счетчик изображений
                num_Counter = num_Counter + 1
                If str_PicLink = str_PicName Then
                    str_ResultText = str_ResultText + _
                    "Иллюстрация №" + Str(num_Counter) + _
                    " " + str_PicLink + " верно" + _
                    " пронумерована" + Chr(13)
                Else
                    str_ResultText = str_ResultText + _
                    "Внимание! Иллюстрация №" + _
                    Str(num_Counter) + _
                    " " + str_PicLink + " неверно" + _
                    " пронумерована" + Chr(13)
                End If
                'Сбросим переменные для хранения
                'новой информации
                str_PicLink = ""
                str_PicName = ""
        End If
    Next
    'сформируем файл отчета
    Set obj_Doc = Documents.Add
    obj_Doc.Activate
    Selection.TypeText str_ResultText


Листинг
12.7.
Макрос для проверки правильности документа

12.6. Заключение

Мы рассмотрели множество вопросов программирования для Microsoft Word. Теперь вы сможете сделать с помощью этого редактора много полезного.

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

title ms.prod ms.assetid ms.date ms.localizationpriority

Finding and Replacing Text or Formatting

word

9ab9f4a7-9833-5a78-56b0-56a161480f18

06/08/2019

medium

Finding and replacing is exposed by the Find and Replacement objects. The Find object is available from the Selection object and the Range object. The find action differs slightly depending upon whether you access the Find object from the Selection object or the Range object.

Finding text and selecting it

If the Find object is accessed from the Selection object, the selection is changed when the find criteria is found. The following example selects the next occurrence of the word «Hello.» If the end of the document is reached before the word «Hello» is found, the search is stopped.

With Selection.Find 
 .Forward = True 
 .Wrap = wdFindStop 
 .Text = "Hello" 
 .Execute 
End With

The Find object includes properties that relate to the options in the Find and Replace dialog box. You can set the individual properties of the Find object or use arguments with the Execute method, as shown in the following example.

Selection.Find.Execute FindText:="Hello", _ 
 Forward:=True, Wrap:=wdFindStop

Finding text without changing the selection

If the Find object is accessed from a Range object, the selection is not changed but the Range is redefined when the find criteria is found. The following example locates the first occurrence of the word «blue» in the active document. If the find operation is successful, the range is redefined and bold formatting is applied to the word «blue.»

With ActiveDocument.Content.Find 
 .Text = "blue" 
 .Forward = True 
 .Execute 
 If .Found = True Then .Parent.Bold = True 
End With

The following example performs the same result as the previous example, using arguments of the Execute method.

Set myRange = ActiveDocument.Content 
myRange.Find.Execute FindText:="blue", Forward:=True 
If myRange.Find.Found = True Then myRange.Bold = True

Using the Replacement object

The Replacement object represents the replace criteria for a find and replace operation. The properties and methods of the Replacement object correspond to the options in the Find and Replace dialog box (Edit menu).

The Replacement object is available from the Find object. The following example replaces all occurrences of the word «hi» with «hello». The selection changes when the find criteria is found because the Find object is accessed from the Selection object.

With Selection.Find 
 .ClearFormatting 
 .Text = "hi" 
 .Replacement.ClearFormatting 
 .Replacement.Text = "hello" 
 .Execute Replace:=wdReplaceAll, Forward:=True, _ 
 Wrap:=wdFindContinue 
End With

The following example removes bold formatting in the active document. The Bold property is True for the Find object and False for the Replacement object. To find and replace formatting, set the find and replace text to empty strings («») and set the Format argument of the Execute method to True. The selection remains unchanged because the Find object is accessed from a Range object (the Content property returns a Range object).

With ActiveDocument.Content.Find 
 .ClearFormatting 
 .Font.Bold = True 
 With .Replacement 
 .ClearFormatting 
 .Font.Bold = False 
 End With 
 .Execute FindText:="", ReplaceWith:="", _ 
 Format:=True, Replace:=wdReplaceAll 
End With

[!includeSupport and feedback]

Понравилась статья? Поделить с друзьями:
  • Vba word cell text
  • Vba word application getopenfilename
  • Vba word application filedialog
  • Vba word application commandbars
  • Vba word activedocument words