Vba word элемент управления содержимым

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

Working with Content Controls

word

b4092c71-a383-f1db-8d68-de69e8d8a86b

06/08/2019

medium

Working with Content Controls

What Are Content Controls?

Content controls are bounded and potentially labeled regions in a document that serve as containers for specific types of content. Individual content controls can contain content such as dates, lists, or paragraphs of formatted text. In some cases, content controls might remind you of forms. However, they are much more powerful, flexible, and useful because they enable you to create rich, structured blocks of content. Content controls enable you to author templates that insert well-defined blocks into your documents. Content controls enable you to:

  • Specify structured regions in a template. Each structured region has its own unique ID so that you can read from and write to it. Examples of types of structured regions (or content controls) are combo boxes, pictures, text blocks, and calendars.

  • Determine the behavior of content controls. Each content control takes up a portion of a document and, as the template author, you can specify what each region does. For example, if you want a region of your template to be a calendar, you insert a calendar content control in that area of the document, which automatically determines what that block of content does. Similarly, if you want a section of a template to display an image, create a picture content control in that area. In this way, you can build a template with predefined block types.

  • Restrict the ability to modify content controls within a document. Each content control can be restricted, so that it cannot be deleted or edited. This is useful if, for example, you have copyright information in a template that the user should be able to read but not edit. Or, as another example, you can also lock a content control that you have placed within a template document so that a user does not accidentally delete the content contained in the content control. This makes templates more robust than in previous versions.

  • Map the contents of a content control to data in a custom XML part. For example, if you insert plain text content controls into cells of a table of stock prices, you can map the content controls in the table cells to nodes in an XML file that contain the current stock prices. When the prices change, an add-in can programmatically update the attached XML file, which is bound to each plain text content control, and the new, updated prices automatically appear in the table.

The easiest way to create a content control is through the user interface (although you can also create them programmatically). To create a content control through the user interface (UI), select the content that you want to turn into a content control (for example, some text or a picture) and then choose the content control type you want from the content controls section of the Developer ribbon. This creates a content control around the selected content.

Content Controls in the Word Object Model

The following table shows the objects in the Word object model that relate to content controls.

Name Description
ContentControl Each ContentControl object represents an individual content control within a document. Use the ContentControls collection to access individual ContentControl objects.
ContentControls Use the ContentControls properties of the Document, Range, and Selection objects to access the collection of content controls. You can also use the SelectContentControlsByTitle method and the SelectContentControlsByTag method of the Document object to access a ContentControls collection that includes specific content controls that all have the same title or tag value.
ContentControlListEntry When a content control is a drop-down list or combo box, the ContentControlListEntry object represents individual items within the list.
ContentControlListEntries Use the DropdownListEntries property of the ContentControl object to access all the items in an individual drop-down list or combo box.

Each of these objects or collections has methods and properties that allow you to work with the content controls both individually and as a collection. Because there are various types of content controls (see the following section «Types of Content Controls»), the ContentControl object has members that might not apply to all the different types of content controls. The following table shows those properties and methods of the ContentControl object that only apply to certain types of content controls.

[!NOTE]
For a complete list of all properties and methods of the ContentControl object, see Content Controls.

Property/Method Applies To
BuildingBlockCategory property BuildingBlock Gallery content controls (wdContentControlBuildingBlockGallery)
BuildingBlockType property BuildingBlock Gallery content controls (wdContentControlBuildingBlockGallery)
DateDisplayFormat property Date content controls (wdContentControlDate)
DateDisplayLocale property Date content controls (wdContentControlDate)
DateStorageFormat property Date content controls (wdContentControlDate)
DropdownListEntries property Combo box and drop-down list content controls (wdContentControlComboBox and wdContentControlDropdownList)
MultiLine property Plain-text content controls (wdContentControlText)
Ungroup method Group content controls (wdContentControlGroup)
SetCheckedSymbol method Check Box content control (wdContentControlCheckBox)
SetUncheckedSymbol method Check Box content control (wdContentControlCheckBox)

Types of Content Controls

There are eight different types of content controls that you can add to a document, each of which is represented in a new enumeration called WdContentControlType.

Content Control Type Description WdContentControlType Constant
A checkbox. wdContentControlCheckBox
Calendar A date-time picker. wdContentControlDate
Building Block Enables the user to choose from specified building blocks. wdContentControlBuildingBlockGallery
Drop-Down List A drop-down list. wdContentControlDropDownList
Group Defines a protected region of a document that users cannot edit or delete. A group control can contain any document items, such as text, tables, graphics, and other content controls. wdContentControlGroup
Combo Box A combo box. wdContentControlComboBox
Picture A picture. wdContentControlBlockPicture
Rich Text A block of rich text. wdContentControlRichText
Plain Text A block of plain text. wdContentControlText

Content Control Events

In addition to the properties and methods available with the content control object model in Word, you can also use several events that allow you to run code when adding or removing a content control or when a user edits a content control. The following list describes each of the events and when the event code runs. All of these events are members of the Document object.

Event Name Description
ContentControlAfterAdd Occurs after adding a new content control to a document. This event runs whether the user adds the content control by using the tools in the UI or adds them by using code.
ContentControlBeforeContentUpdate Occurs before Word updates the content in a content control.
ContentControlBeforeDelete Occurs before a user deletes a content control. This event runs whether the user deletes the content control by using the tools in the UI or deletes them by using code.
ContentControlBeforeStoreUpdate Occurs before Word updates the contents of a content control from data in the document’s data store.
ContentControlOnEnter Occurs when a user enters a content control.
ContentControlOnExit Occurs when a user exits a content control.

Working with the Code

Whether you want to add a content control, delete a content control, or access and manipulate existing content controls, you can do it with code. The following sections are just a few samples of what you can do.

Adding a Content Control

As mentioned previously, there are eight different types of content controls that you can add to your documents. Use the Add method of the ContentControls collection to add a content control to a document. The following example adds a date picker to the active document and sets the date value to the current date.

Sub AddDatePicker() 
 
    Dim objCC As ContentControl 
    Dim objDate As Date 
 
    Set objCC = ActiveDocument.ContentControls _ 
        .Add(wdContentControlDate) 
    objDate = Date 
    objCC.Range.Text = objDate 
     
End Sub

Use the same basic construction to add any of the different types of content controls to a document.

Adding a Title to a Content Control

Use the Title property to add a title to a content control. This is text that users see, and it can help them to know what type of data to enter into the content control. The following example adds a new plain-text content control to the active document and sets the title, or display text, for the control.

Sub SetTitleForContentControl() 
 
    Dim objCC As ContentControl 
     
    Set objCC = ActiveDocument.ContentControls _ 
        .Add(wdContentControlText) 
         
    objCC.Title = "Please enter your name" 
     
End Sub

Modifying Placeholder Text to a Content Control

Placeholder text is temporary text. It can be a simple one-word or two-word description (similar to the title) or it can be a more thorough description (such as numbered steps). Modifying the placeholder text is the same regardless of the type of content control or the expected contents of the content control. The following example adds a drop-down list to the active document, sets the placeholder text for the control, and then fills the list with the names of several animals.

Sub SetPlaceholderText() 
 
    Dim objCC As ContentControl 
     
    Set objCC = Selection.ContentControls _ 
        .Add(wdContentControlComboBox) 
    objCC.Title = "Favorite Animal" 
    objCC.SetPlaceholderText _ 
        Text:="Please select your favorite animal " 
     
    'List entries 
    objCC.DropdownListEntries.Add "Cat" 
    objCC.DropdownListEntries.Add "Dog" 
    objCC.DropdownListEntries.Add "Horse" 
    objCC.DropdownListEntries.Add "Monkey" 
    objCC.DropdownListEntries.Add "Snake" 
    objCC.DropdownListEntries.Add "Other" 
 
End Sub

These are just a few of the ways that you can use the object model to manipulate content controls in your documents. For more examples, see the How To section.

[!includeSupport and feedback]

title ms.prod ms.assetid ms.date

Working with Content Controls

word

b4092c71-a383-f1db-8d68-de69e8d8a86b

06/08/2017

Working with Content Controls

What Are Content Controls?

Content controls are bounded and potentially labeled regions in a document that serve as containers for specific types of content. Individual content controls can contain content such as dates, lists, or paragraphs of formatted text. In some cases, content controls might remind you of forms. However, they are much more powerful, flexible, and useful because they enable you to create rich, structured blocks of content. Content controls enable you to author templates that insert well-defined blocks into your documents. Content controls enable you to:

  • Specify structured regions in a template. Each structured region has its own unique ID so that you can read from and write to it. Examples of types of structured regions (or content controls) are combo boxes, pictures, text blocks, and calendars.

  • Determine the behavior of content controls. Each content control takes up a portion of a document and, as the template author, you can specify what each region does. For example, if you want a region of your template to be a calendar, you insert a calendar content control in that area of the document, which automatically determines what that block of content does. Similarly, if you want a section of a template to display an image, create a picture content control in that area. In this way, you can build a template with predefined block types.

  • Restrict the ability to modify content controls within a document. Each content control can be restricted, so that it cannot be deleted or edited. This is useful if, for example, you have copyright information in a template that the user should be able to read but not edit. Or, as another example, you can also lock a content control that you have placed within a template document so that a user does not accidentally delete the content contained in the content control. This makes templates more robust than in previous versions.

  • Map the contents of a content control to data in a custom XML part. For example, if you insert plain text content controls into cells of a table of stock prices, you can map the content controls in the table cells to nodes in an XML file that contain the current stock prices. When the prices change, an add-in can programmatically update the attached XML file, which is bound to each plain text content control, and the new, updated prices automatically appear in the table.

The easiest way to create a content control is through the user interface (although you can also create them programmatically). To create a content control through the user interface (UI), select the content that you want to turn into a content control (for example, some text or a picture) and then choose the content control type you want from the content controls section of the Developer ribbon. This creates a content control around the selected content.

Content Controls in the Word Object Model

The following table shows the objects in the Word object model that relate to content controls.

Name Description
ContentControl Each ContentControl object represents an individual content control within a document. Use the ContentControls collection to access individual ContentControl objects.
ContentControls You can use the ContentControls properties of the Document, Range, and Selection objects to access the collection of content controls. You can also use the SelectContentControlsByTitle method and the SelectContentControlsByTag method of the Document object to access a ContentControls collection that includes specific content controls that all have the same title or tag value.
ContentControlListEntry When a content control is a drop-down list or combo box, the ContentControlListEntry object represents individual items within the list.
ContentControlListEntries Use the DropdownListEntries property of the ContentControl object to access all the items in an individual drop-down list or combo box.
Each of these objects or collections has methods and properties that allow you to work with the content controls both individually and as a collection. Because there are various types of content controls (see the following section «Types of Content Controls»), the ContentControl object has members that might not apply to all the different types of content controls. The following table shows those properties and methods of the ContentControl object that only apply to certain types of content controls.

Note: For a complete list of all properties and methods of the ContentControl object, see Content Controls.

Property/Method Applies To
BuildingBlockCategory property BuildingBlock Gallery content controls (wdContentControlBuildingBlockGallery)
BuildingBlockType property BuildingBlock Gallery content controls (wdContentControlBuildingBlockGallery)
DateDisplayFormat property Date content controls (wdContentControlDate)
DateDisplayLocale property Date content controls (wdContentControlDate)
DateStorageFormat property Date content controls (wdContentControlDate)
DropdownListEntries property Combo box and drop-down list content controls (wdContentControlComboBox and wdContentControlDropdownList)
MultiLine property Plain-text content controls (wdContentControlText)
Ungroup method Group content controls (wdContentControlGroup)
SetCheckedSymbol method Check Box content control (wdContentControlCheckBox)
SetUncheckedSymbol method Check Box content control (wdContentControlCheckBox)

Types of Content Controls

There are eight different types of content controls that you can add to a document, each of which is represented in a new enumeration called WdContentControlType.

Content Control Type Description WdContentControlType Constant
A checkbox. wdContentControlCheckBox
Calendar A date-time picker. wdContentControlDate
Building Block Enables the user to choose from specified building blocks. wdContentControlBuildingBlockGallery
Drop-Down List A drop-down list. wdContentControlDropDownList
Group Defines a protected region of a document that users cannot edit or delete. A group control can contain any document items, such as text, tables, graphics, and other content controls. wdContentControlGroup
Combo Box A combo box. wdContentControlComboBox
Picture A picture. wdContentControlBlockPicture
Rich Text A block of rich text. wdContentControlRichText
Plain Text A block of plain text. wdContentControlText

Content Control Events

In addition to the properties and methods available with the content control object model in Word, you can also use several events that allow you to run code when adding or removing a content control or when a user edits a content control. The following list describes each of the events and when the event code runs. All of these events are members of the Document object.

Event Name Description
ContentControlAfterAdd Occurs after adding a new content control to a document. This event runs whether the user adds the content control by using the tools in the UI or adds them by using code.
ContentControlBeforeContentUpdate Occurs before Word updates the content in a content control.
ContentControlBeforeDelete Occurs before a user deletes a content control. This event runs whether the user deletes the content control by using the tools in the UI or deletes them by using code.
ContentControlBeforeStoreUpdate Occurs before Word updates the contents of a content control from data in the document’s data store.
ContentControlOnEnter Occurs when a user enters a content control.
ContentControlOnExit Occurs when a user exits a content control.

Working with the Code

Whether you want to add a content control, delete a content control, or access and manipulate existing content controls, you can do it with code. The following sections are just a few samples of what you can do.

Adding a Content Control

As mentioned previously, there are eight different types of content controls that you can add to your documents. Use the Add method of the ContentControls collection to add a content control to a document. The following example adds a date picker to the active document and sets the date value to the current date.

Sub AddDatePicker() 
 
    Dim objCC As ContentControl 
    Dim objDate As Date 
 
    Set objCC = ActiveDocument.ContentControls _ 
        .Add(wdContentControlDate) 
    objDate = Date 
    objCC.Range.Text = objDate 
     
End Sub

You can use the same basic construction to add any of the different types of content controls to a document.

Adding a Title to a Content Control

Use the Title property to add a title to a content control. This is text that users see, and it can help them to know what type of data to enter into the content control. The following example adds a new plain-text content control to the active document and sets the title, or display text, for the control.

Sub SetTitleForContentControl() 
 
    Dim objCC As ContentControl 
     
    Set objCC = ActiveDocument.ContentControls _ 
        .Add(wdContentControlText) 
         
    objCC.Title = "Please enter your name" 
     
End Sub

Modifying Placeholder Text to a Content Control

Placeholder text is temporary text. It can be a simple one-word or two-word description (similar to the title) or it can be a more thorough description (such as numbered steps). Modifying the placeholder text is the same regardless of the type of content control or the expected contents of the content control. The following example adds a drop-down list to the active document, sets the placeholder text for the control, and then fills the list with the names of several animals.

Sub SetPlaceholderText() 
 
    Dim objCC As ContentControl 
     
    Set objCC = Selection.ContentControls _ 
        .Add(wdContentControlComboBox) 
    objCC.Title = "Favorite Animal" 
    objCC.SetPlaceholderText _ 
        Text:="Please select your favorite animal " 
     
    'List entries 
    objCC.DropdownListEntries.Add "Cat" 
    objCC.DropdownListEntries.Add "Dog" 
    objCC.DropdownListEntries.Add "Horse" 
    objCC.DropdownListEntries.Add "Monkey" 
    objCC.DropdownListEntries.Add "Snake" 
    objCC.DropdownListEntries.Add "Other" 
 
End Sub

These are just a few of the ways that you can use the object model to manipulate content controls in your documents. For more examples, see the How To section.

1 / 1 / 0

Регистрация: 03.11.2009

Сообщений: 92

1

06.10.2010, 11:21. Показов 7772. Ответов 13


Студворк — интернет-сервис помощи студентам

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

краткое имя

и

значение

(ну и понятно, индекс, определяющий порядок следования). В ходе работы

краткое имя

выбранного элемента списка данного ContentControl получаю функцией, например: ActiveDocument.ContentControls(2).Range, а вот какой функцией вытащить

значение

не знаю. (Термины краткое имя и значение взяты из формы заполнения поля со списком).

С уважением



0



Busine2009

Заблокирован

06.10.2010, 16:26

2

Mikkelle,
напиши, как делаешь поле со списком (куда нажимаешь).



0



1 / 1 / 0

Регистрация: 03.11.2009

Сообщений: 92

06.10.2010, 16:33

 [ТС]

3

2007
Разработчик-Элементы управления-Поле со списком



0



Busine2009

Заблокирован

06.10.2010, 17:08

4

Цитата
Сообщение от Mikkelle
Посмотреть сообщение

получаю функцией

это не функция. Это свойство или метод.

Добавлено через 10 минут
Mikkelle,

Visual Basic
1
2
3
Sub m_1()
MsgBox ActiveDocument.ContentControls(1).DropdownListEntries(3).Value
End Sub



0



1 / 1 / 0

Регистрация: 03.11.2009

Сообщений: 92

06.10.2010, 17:41

 [ТС]

5

DropdownListEntries(3) — конкретное указание на номер в списке. А как получить значение Value для выбранного в ContentControls(1) элемента?



0



Busine2009

Заблокирован

06.10.2010, 17:43

6

Mikkelle,
так это надо программу писать что ли? Реагирование на событие «Выбор».



0



1 / 1 / 0

Регистрация: 03.11.2009

Сообщений: 92

06.10.2010, 17:45

 [ТС]

7

Так и речь про то. Если в обычном комбо присутствует параметр ListIndex то тут его нет!



0



Busine2009

Заблокирован

06.10.2010, 17:51

8

Mikkelle,
VBA не видит новых (в смысле сделанных в Word 2007) элементов управления.



0



1 / 1 / 0

Регистрация: 03.11.2009

Сообщений: 92

06.10.2010, 17:54

 [ТС]

9

Нет вашей правды. Краткое имя выбранного элемента списка данного ContentControl вытаскивается функцией, например: ActiveDocument.ContentControls(2).Range. VBA все видет и даже различает эти самые ContentControls.



0



Busine2009

Заблокирован

06.10.2010, 17:59

10

Mikkelle,
если вставить старый элемент (Разработчик — Элементы управления — Инструменты из предыдущих версий — Элементы ActiveX — Поле со списком (Элемент ActiveX)), то он появляется в VBA (ThisDocument (имеется ввиду этот документ, где находится список, а не шаблон) — Левый выпадающий список (там появится этот ActiveX).



0



1 / 1 / 0

Регистрация: 03.11.2009

Сообщений: 92

06.10.2010, 18:05

 [ТС]

11

Ну, скорее всего, это не элемент управления, как ActiveX, а некое поле с навороченным интерфейсом. Поменял бы в сущности его на Combo из ActiveX, но ни как не пойму, как исключить вывод на печать данного элемента. Может тогда здесь что присоветуете?



0



Busine2009

Заблокирован

06.10.2010, 18:44

12

Mikkelle,
а самому не судьба тыкать?
Я вот так натыкал: BorderStyle — 0, ShowDropButtonWhen — 1.



0



1 / 1 / 0

Регистрация: 03.11.2009

Сообщений: 92

07.10.2010, 12:35

 [ТС]

13

Так я поначалу я ComboBox не рассматривал. Сейчас попробовал, но оказалось, что длинный текст не форматируется как ContentControls. Там работает действительно как текстовое поле, занимая, что в строке, что в ячейке таблицы минимально-необходимое пространство.
Спасибо за подсказку, но буду пробовать искать решение для ContentControls.

Добавлено через 14 часов 40 минут
Нашел решение! Действовать приходится перебором, сравнивая выбранное

краткое имя

с имеющимися в списке.



0



letu

11.04.2014, 16:10

14

за столько времени ничего не изменилось, в 2013 офисе та же беда — краткое имя элемента управления содержимым можно получить сразу, а для значения, ради которого и ставился этот элемент, приходится перебирать краткие имена

Microsoft Word Content Controls VBA (Visual Basic for Applications)

Content Controls

In-line user controls which can be embedded in the document withing a range or selection. Microsoft Word VBA object offers ten Content Controls listed below which can be short hand the programming and provide various user input methods:

Syntax

expression.ContentControls.Add(Type)

List Content Controls

  1. wdContentControlBuildingBlockGallery
  2. wdContentControlCheckBox
  3. wdContentControlComboBox
  4. wdContentControlDate
  5. wdContentControlDropdownList
  6. wdContentControlGroup
  7. wdContentControlPicture
  8. wdContentControlRepeatingSection
  9. wdContentControlRichText
  10. wdContentControlText

Example

Following code will create three labels and three controls to take user input on a blank document. Note to arrange multiple controls I have used a special symbol to avoid overlapping of the control on the page which I seek through MoveUntil method by passing it in Cset parameter.

RichTextBox Control

Public Sub AddRichTextContentControl()
On Error GoTo errh
    Dim objContentControl As ContentControl
    Dim oDocument As Document
    
    
    'Bind active document reference
    Set oDocument = ActiveDocument
    
    'Type blank
    Selection.Text = "|"
    
    'Move selection at the start
    Selection.Collapse Direction:=WdCollapseDirection.wdCollapseStart
    
    'Populate label
    Selection.Text = "Enter name : "
    
    'Move selection at the end
    Selection.MoveUntil cset:="|"
    
    'Add textbox
    Set objContentControl = Selection.ContentControls.Add(Type:=wdContentControlRichText)
    

errh:
    'Memory cleanup
    If Not objContentControl Is Nothing Then
        Set objContentControl = Nothing
    End If
    If Not oDocument Is Nothing Then
        Set oDocument = Nothing
    End If
    
If Err.Number <> 0 Then
End If
End Sub

Output

ComboBox Control

Public Sub ComboBoxAddContentControl()
On Error GoTo errh
    Dim objContentControl As ContentControl
    Dim oDocument As Document
    
    
    'Bind active document reference
    Set oDocument = ActiveDocument
    
    'Type blank
    Selection.Text = "|"
    
    'Move selection at the start
    Selection.Collapse Direction:=WdCollapseDirection.wdCollapseStart
    
    'Populate label
    Selection.Text = "Select a color : "
    
    'Move selection at the end
    Selection.MoveUntil cset:="|"
    
    'Bind control by creating
    Set objContentControl = Selection.ContentControls.Add(Type:=wdContentControlComboBox)
    
    'Add some items in combobox
    With objContentControl
        .DropdownListEntries.Add "RED"
        .DropdownListEntries.Add "YELLOW"
        .DropdownListEntries.Add "GREEN"
        .DropdownListEntries.Add "BLACK"
        .DropdownListEntries.Add "WHITE"
    End With
    
    
errh:
    'Memory cleanup
    If Not objContentControl Is Nothing Then
        Set objContentControl = Nothing
    End If
    If Not oDocument Is Nothing Then
        Set oDocument = Nothing
    End If
    
If Err.Number <> 0 Then
End If
End Sub

Output

Date Control

Public Sub DateAddContentControl()
On Error GoTo errh
    Dim objContentControl As ContentControl
    Dim oDocument As Document
    
    
    'Bind active document reference
    Set oDocument = ActiveDocument
    
    'Type blank
    Selection.Text = "|"
    
    'Move selection at the start
    Selection.Collapse Direction:=WdCollapseDirection.wdCollapseStart
    
    
    'Populate label
    Selection.Text = "Select Date : "
    
    'Move selection at the end
    Selection.MoveUntil cset:="|"
    
    'Bind control by creating
    Set objContentControl = Selection.ContentControls.Add(Type:=wdContentControlDate)
errh:
    'Memory cleanup
    If Not objContentControl Is Nothing Then
        Set objContentControl = Nothing
    End If
    If Not oDocument Is Nothing Then
        Set oDocument = Nothing
    End If
    
If Err.Number <> 0 Then
End If
End Sub

Output

Similarly you can modify code to populate rest of the control in running document commentary. It can build a simple data entry form to get user inputs.

Sorting in Microsoft Word using VBA (Visual Basic for Applications)

I’ve been developing some “smart” forms a government department in the last few months. These forms had to be developed in good old MS Word. Now, Word is not really suited to creating tightly controlled forms, but, in my case it’s all I had to work with and I’ve had to work within the limitations presented to me. The only real solution available was to use Word Content Controls and then to protect portions of the document that users shouldn’t be able to edit. I’ve managed to get things working fairly well and thought it worth sharing a bit of code I’ve developed along the way that should help anyone working with Microsoft Word Content Controls and VBA.

Data Validation

If you’re doing forms then data validation is critical. It’s pretty straightforward if you’re working with content controls if you make use of the ContentControlOnExit event. For example, here’s a bit of basic validation that ensures the value entered into a field is currency:

Private Sub Document_ContentControlOnExit(ByVal CC As contentControl, Cancel As Boolean)
  Dim sngTotalCost As Single
  Dim oCC As contentControl
  Select Case CC.Tag
    Case "sTotalCost"
      If Not validateCurrency(CC.Range.Text) Then
        Cancel = True
        Beep
        CC.Range.Select
        Exit Sub
      Else
        CC.Range.Text = Format(parseCurrency(CC.Range.Text), "$#,###0.00")
      End If
  End Select
End Sub

Public Function validateCurrency(sValue As String) As Boolean
  Dim iLoop As Integer
  Dim bReturn As Boolean
  Dim iAsc As Integer
  
  On Error GoTo errorHandler
  
  bReturn = False
  
  validateCurrency = bReturn
  
  sValue = Trim(sValue)
  sValue = Replace(sValue, "$", "")
  sValue = Replace(sValue, ",", "")
  
  If Len(sValue) = 0 Then
    validateCurrency = True
    Exit Function
  End If
  
  For iLoop = 1 To Len(sValue)
    iAsc = Asc(Mid(sValue, iLoop))
    
    If iAsc = Asc(".") Or (iAsc >= Asc("0") And iAsc <= Asc("9")) Then
    
    Else
      Exit Function
    End If
  Next iLoop
  validateCurrency = True
  Exit Function
errorHandler:
  MsgBox "An error has occurred" & vbCrLf & "Module: ThisDocument" & vbCrLf & "Procedure: validateCurrency" & vbCrLf & "Error Number: " & Err.Number & vbCrLf & "Description: " & Err.Description, vbOKOnly
  Err.Clear
End Function

Public Function parseCurrency(sValue As String) As Single
  Dim iLoop As Integer
  Dim iAsc As Integer
  On Error GoTo errorHandler
  parseCurrency = 0
  
  sValue = Trim(sValue)
  sValue = Replace(sValue, "$", "")
  sValue = Replace(sValue, ",", "")
  
  If Len(sValue) = 0 Then
    parseCurrency = 0
    Exit Function
  End If
  
  For iLoop = 1 To Len(sValue)
    iAsc = Asc(Mid(sValue, iLoop))
    
    If iAsc = Asc(".") Or (iAsc >= Asc("0") And iAsc <= Asc("9")) Then
    
    Else
      Exit Function
    End If
  Next iLoop
  parseCurrency = Round(CSng(sValue), 2)
  Exit Function
errorHandler:
  MsgBox "An error has occurred" & vbCrLf & "Module: ThisDocument" & vbCrLf & "Procedure: parseCurrency" & vbCrLf & "Error Number: " & Err.Number & vbCrLf & "Description: " & Err.Description, vbOKOnly
  Err.Clear
End Function

In this code we simply check the tag of each content control as users move to the next one. Content control tags are set on the Developer tab from within Word. If the control has a tag we’re interested in then the value (Range.Text) is run through the ValidateCurrency function. If it is valid then the parseCurrency function is used to format the value correctly and write it back to the content control contents. If the value entered isn’t valid then a user alert is raised and the focus is returned to the content control

Excel Style “Automatic” Calculations

If you’ve got data validation sorted out it’s a simple step to have read only fields in your forms whose values are derived from user entered fields. This bit of code takes the value of a currency field, multiplies it by 1.1 and writes the value into a second field.

Private Sub Document_ContentControlOnExit(ByVal CC As contentControl, Cancel As Boolean)
  Dim sngTotalCost As Single
  Dim oCC As contentControl
  Select Case CC.Tag
    Case "sTotalCost"
      If Not validateCurrency(CC.Range.Text) Then
        Cancel = True
        Beep
        CC.Range.Select
        Exit Sub
      Else
        CC.Range.Text = Format(parseCurrency(CC.Range.Text), "$#,###0.00")
      End If
      Set oCC = ActiveDocument.SelectContentControlsByTag("sTotalCost").Item(1)
      sngTotalCost = parseCurrency(oCC.Range.Text)
      
      Set oCC = ActiveDocument.SelectContentControlsByTag("sTotalCostGST").Item(1)
      With oCC
        .LockContents = False
        .Range.Text = Format(sngTotalCost * 1.1, "$#,###0.00")
        .LockContents = True
      End With
  End Select
  Set oCC = Nothing

End Sub 

It’s pretty simple to see what’s happening here. The value in the content control with the tag sTotalCost is validated for currency, and if a correct value the number has a calculation applied to it and the resultant value is written to a second content control with the tag sTotalCostGST. Note that I use the LockContents method to be able to write to the second content control and then use it again to make it read only.

Changing Document Format Based on Content Control Value

The last thing I’ll share is using the value in a content control to change some format in a Word document. In this case I simply set the font color of the content control based on the value selected in the control

Private Sub Document_ContentControlOnExit(ByVal CC As contentControl, Cancel As Boolean)
  Dim sngTotalCost As Single
  Dim oCC As contentControl
  Select Case CC.Tag
    Case "sTag1", "sTag2", "sTag3"
      If CC.Range.Text = "Yes" Then
        CC.Range.Font.ColorIndex = wdGreen
      End If
      If CC.Range.Text = "No" Then
        CC.Range.Font.ColorIndex = wdRed
      End If
  End Select
  Set oCC = Nothing
End Sub

These content controls were of the dropdown list type. When “Yes” is selected the font color is set to green with the ColorIndex property. When set to “No” the Font.ColorIndex is set to Red. Pretty simple.

Like this post? Please share to your friends:
  • Vba вывод в word
  • Vba word что такое merge
  • Vba word чтение таблиц
  • Vba выбрать цвет ячейки excel
  • Vba вставка текста в таблицу word