Fire Subroutine when user leaves a date field ContentControl Word VBA - vba

Edit: I've updated the post with more info.
I have a Content Control inside a header in Word in which I have a date time picker. I'm trying to fire the _ContentControlOnExit event when the user leaves the focus (blurs) of the picker.
Let's suppose I've manually created a Content Control and I've assigned it a Date Picker. I've also tagged it with the value date.
I want that each time the date is changed, I perform a subroutine that will insert a text value to another ContentControl tagged tide-level. I tried the code below with no success.
Please, note that the date ContentControl is inside a header in the Word Document.
Private Sub ActiveDocment_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)
If (ContentControl.Type = wdContentControlDate) Then
MsgBox "Let's do it! Write the tide levels"
dateObj = ActiveDocument.SelectContentControlsByTag("tide-level")
dateObj.Range.Text = "wwwoohooo Tide Levels!"
Cancel = True
End If
End Sub
I remember reading somewhere that whenever you have content in the header, it seems things get problematic...
Any ideas?
P.S:
Currently using Word 365 - VBA

Based on the name of the procedure in the question - ActiveDocment_ContentControlOnExit - it appears the event handler was not generated automatically by Word and that it is therefore not in the ThisDocument class module of the document that contains the content controls. The name of the event handler (generated by the VBA editor) is usually Document_ContentControlOnExit.
The content control event handlers must be in ThisDocument. Theoretically, they could be typed manually, but Word doesn't always recognize manually typed event handlers. So it's better to use the VBA Editor's automatic "stub" generation to get the structures:
Open the ThisDocument module for the document that contains the content control.
In the code page window, at the top left, select "Document" from the drop-down.
from the top-right select the event to be inserted.
At this point, the VBA editor will create the "stub" for you - all that's needed is the code to be executed.
Note about the content control being in the header: This event does fire as long as focus when exiting remains in the header. If, however, the user double-clicks in the document body in order to exit the header the event doesn't fire. (At least, not in my tests.) If this is a problem you may want to put this field in the body of the document with a second, linked content control in the header to reflect the selection. Doing this is a bit complex (requires a Custom XML Part in the document to manage the linked information), but the version of Word you're using should have a tool for setting it up.

the macro name should be:
Docment_ContentControlOnExit
NOT:
ActiveDocment_ContentControlOnExit

Related

In a VBA Userform, which event is triggered when exiting a filed

I'm using Microsoft Office Professional Plus (64 bit) on a Windows 10 (64 bit) platform. I have a subroutine that is processed when I make a change to a Userform field called MyDate. It's called Private Sub MyDate_AfterUpdate(). It's the second field on a form. It works fine as long as the contents of the MyDate field are edited. However, if the user doesn't need to update the contents of the MyDate field because they accept the default of the field and just presses the tab key past that second field, I'd still like the subroutine to be executed. What event can I use to activate code when I simply tab through the field and don't necessarily edit the contents? Thanks for looking at this.
If you look at the top of the code panes, you'll notice two dropdowns. The left one contains all interfaces and event providers you can implement in that class (a UserForm is a class).
Select your MyDate control from that dropdown; the right-side dropdown is now listing every event you could handle for this MyDate control:
In this particular case, the Exit event seems a good candidate:
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
'make Cancel.Value = True to prevent exiting the control.
'...ideally... make that conditional...
End Sub
By consistently using these dropdowns to let the VBE generate event handler procedures for you (instead of typing them up from memory), you avoid getting it wrong... and getting an event handler signature wrong can do anything from literally nothing at all, to compile errors if you're lucky, or weird and hard-to-diagnose behavior if you're less lucky.

VBA event handler for checking cells in a table in Word

I have a table in Word:
Table Example
The table is bookmarked in the document, as it can appear in different places in the document. I access the table using the bookmark like this:
Set Tbl = ActiveDocument.Bookmarks("bookmarkname").Range.Tables(1)
I have a script that checks if a cell has a checkmark and displays a Msgbox when it has a checkmark and shouldn’t, based on certain criteria of the Row and Column name.
Here’s the question:
I would like this script to fire by a Cell_OnLeave type of event, so that when user leaves a cell, script will run. Is this possible?
If this is not possible, I would like the script to fire when user leaves the table, and script can check the whole table? Maybe a bookmark_deselected event would work for that? How could this be done?
It is possible to create custom events for table cells in Word.
Since the code is quite long, I'll just link to an example document and a GitHub gist.
I tried to comment the code as much as possible to make it understandable.
The module creates on enter, on change and on exit events for table cells and an event manager to define each event's behavior.
If you don't want to read everything, use the module by modifying the CellEventManager subroutine.
The sub receives the event type and the cell that triggered the event, so you can properly define event responses to your likings.
I also implemented a Cancel functionality for the OnExit event: Set CellEventManager = Fail during the handling of a OnExit event to prevent the selection from leaving the cell.
Only the built-in events can be handled in Word. There are no specific events for either tables or bookmarks. The only event that gets you anywhere close is the WindowSelectionChange event which fires each time the selection is changed, i.e. each time the insertion point is moved.

Explanation of vba code in a word document having .docm extension

I have a Microsoft Word document with .docm format. A first glance it does not contain any macros (as when clicking the following on the ribbon; View -> Macros -> View macros pops up a window having an empty list).
But when enabling the Developer ribbon tab, and clicking the Visual Basic icon there, and then selecting the Document and ContentControlonEnter from the dropdowns in the VB window the following code appears:
Private Sub Document_ContentControlOnEnter(ByVal ContentControl As ContentControl)
Dim i As Long, j As Long
With ActiveDocument
If ContentControl.Title = "Classification" Then
ContentControl.DropdownListEntries.Clear
For i = 1 To .ContentControls.Count
If Left(.ContentControls(i).Title, 5) = "Level" Then
j = j + 1
ContentControl.DropdownListEntries.Add Text:=j & " - " & .ContentControls(i).Range.Text
End If
Next
End If
End With
End Sub
Selecting the other options in the dropdowns give only "blank" code (that is they contain only function declarations followed by theEnd keyword).
My question is what is the code meant to do?
*
Details:
The Word document in question contains hyperlinks to parts of the same document and a couple of links to Word files and Excel files of the same folder. It also contains lots of content control boxes, which I'm guessing is the focus of the code (as the code contains the ContentControl keyword)
Content controls can trigger macros when the user enters and exits them. Microsoft made the design decision that all content controls should trigger the same "events" - Document_ContentControlOnEnter / Document_ContentControlOnExit - and that the code in the event needs to check which content control was entered / exited.
Content controls are considered as part of the Document because the Document can trigger events. That's why they're in (and MUST be in) the ThisDocument class module.
(Note: View Macros can only show you PUBLIC SUB procedures with no arguments that are located in "normal" code modules. Any Private Sub, any Function, anything that takes a parameter and anything in a class module will not appear in that list. So you can't use that list to determine whether a document contains any code.)
The If ContentControl.Title = "Classification" Then checks which content control was entered. (Note: it usually makes more sense to use Select Case rather than If, especially when the event needs to distinguis between multiple content controls.) What's inside the If only executes if it was a content control with the Title "Classification". (Note that more than one content control can have the same Title, so more than one content control could run the code.)
If another content control is entered, the event is still fired, but nothing happens (in this case).
Catalin Pop correctly explained that the code is, in essence, "resetting" the drop down list.
Legacy Form fields use a similar pattern - macros can fire when the user enters/exits an form field. But the design for that was you had to create a Public Sub and assign that to the form field in the Properties.
I think the logic here is quite simple.
Basically the code searches for a content control named Classification within the entire document.
After it finds it, it clears all of its drowdown entries - like a reset.
After the cleaning part it again searches through the entire document for all content control that start with word "Level" and it collect the text for those controls and their order in appearance.
With this info collected it then fills the dropdown optios for the classification control above. (e.g. 1 Level X, 2 Level Y.. - based on what it finds in the document for controls starting with Level in their name)

Word - how to uncheck checkboxes?

I have 4 checkboxes but we need to restrict selection to just a single one, meaning if you check the first, the other 3 will go unchecked. I know we could use ActiveX radio buttons but we'd prefer to avoid ActiveX if possible, plus with check boxes we have more control over the layout.
I've set the name of the checkbox appropriately to Check1:
And then I've put this very basic script into the Visual Basic section:
Private Sub Check1_Click()
Check1.Enabled = True
Check2.Enabled = False
Check3.Enabled = False
Check4.Enabled = False
End Sub
But unfortunately checking the first box doesn't uncheck the next 3.
Any ideas please? Thank you!
If these are Content Controls, as you indicate, then they do not have a CLICK event. Nor can they be identified by VBA by their Title property. The code you show us is for ActiveX controls, which you say you don't want to use...
Working with content control events is not as simple and intuitive as with ActiveX controls. Similar to form fields, Content Controls only have "editing" events that trigger on the user entering and exiting the content control. These events are available in the ThisDocument module, in the Document category.
The same ContentControlOnExit event triggers for ALL content controls in the document, so you need a Select Case or If conditional to query the ContentControl argument in order to know which content control was exited.
In order to address the other checkboxes you need to use the Document.SelectContentControlsByTitle (or ...ByTag) method which returns an array of all content controls with that title (or tag).
If you really want to emulate a "click" event then you need to insert a Custom XML Part in the document with nodes linked to the content controls. When the user changes the state of the control the ContentControlBeforeStoreUpdate event will trigger, letting you take action.
The property you need is Value, not Enabled.
The purpose of property Enabled is to prevent a control from being changed by user.
Additionaly, you need to prevent it from the events cascade. It means that when you change programatically the value of Check2, this will trigger Private Sub Check2_Click() and so on.
In order to make it work you should change your code like that:
Private Sub Check1_Click()
If Check1.Value Then
Check1.Value = True
Check2.Value = False
Check3.Value = False
Check4.Value = False
End If
End Sub
and similarly for the other check boxes.
For your purpose radio buttons will be better choice. Radio buttons have built-in functionality to uncheck currently selected button if other one is checked.

Word 2010 VBA Checkboxes

Hopefully an easy one.
I've got a Word document littered with Checkboxes. Is there any way to access these checkboxes as a collection I can loop through and check/set properties such as ID and Value?
For reference, I've already tried the ActiveDocument.ContentControls collection; it's empty.
I've also tried ActiveDocument.Fields. This actually contains the same number of checkboxes as there are on the page, but I can't cast it to a Checkbox to access the properties I need.
One final question, is it possible to dynamically assign an event handler to the click?
Thank you in advance
The collection of all ActiveX fields embedded in your document (let's say its name is ThisDocument) is the collection ThisDocument.Fields. The items of this collection are objects of class Field.
To query the value of the objects in this collection, you'd use something along the lines of:
ThisDocument.Fields.Item(1).OLEFormat.Object.Value
To add code to the event handlers, just right-click on the ActiveX control, and then select "View Code" from the context menu. You'll get the Click event handler:
Private Sub CheckBox1_Click()
' empty if event handler not set, VBA code otherwise '
End Sub
To insert code dynamically, you need to manipulate the Code Module directly, and add the event handlers line by line. This might be tricky but, basically, you'd do something like:
ThisDocument _
.VBProject _
.VBComponents(ThisDocument.CodeName) _
.CodeModule _
.InsertLines(<<Line>>, <<String>>)
where <<Line>> is where you want to insert (number), and <<String>> is the text that you want to insert. Be careful not to insert in the middle of an existing Sub, Function or custom type definition (obviously).