VBA event handler for checking cells in a table in Word - vba

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.

Related

Fire Subroutine when user leaves a date field ContentControl Word 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

Update or refresh Word ContentControls

I have a scenario whereby I need to (programmatically) add ContextControls to a Word table.
My example is when a user adds a ContentControl to a table (first cell) then adds a repeating ContentControl to that row - this is perfect!
If the user then goes to cell 2 of a 2 cell table (to keep things simple) and adds another ContentControl - keeping in mind this row is already a repeating ContentControl and now just has an additional ContentControl added, the data does not repeat.
If I go into my Word ribbon - Developer, then flick design on and off, the data all appears fine again (almost like the repeating ContentControl was updated / refreshed). I'm wondering - is there a way to do this through code?
Something like repeating ContentControl.Update / Refresh / Reload (none of those exist).
Right now - I'll even accept if I can do this through the Word application itself, but I will be converting this to code.
For anyone needing the answer to this:
After 3 days, I've decided that the best way to accomplish this task, is by calling the .ToggleFormsDesign method twice.
This will basically "refresh / update" the binding on the repeating ContentControl
With ActiveDocument
.ToggleFormsDesign
.ToggleFormsDesign
End With
Calling this method back to back, will have no UI / visual impact (i.e. the user will not notice anything).
MSDN Link to the Method

Order of Events for the SheetFollowHyperlink Event

I have a workbook that lists people's names and overall performance for the past few weeks. I was asked to make it so that when their names are clicked, the details for that person would show. The solution I came up with at the time was to point all of the hyperlinks to a sheet that reminded them to turn on their macros.
In the WorkSheet_Activate event, I redirected them to another sheet that populated with the details for the person they had selected. This works fine. If the user doesn't have their macros turned on, they get a friendly reminder, but if they do, they immediately get redirected. There's just one problem. Because the hyperlink takes them somewhere else first, it causes the infamous "screen flicker".
On researching, I found the FollowHyperlink Events (I think the workbook level event would be most suitable for my purposes, though). However, before I get started rebuilding it, I wanted to make sure that this would solve the "screen flicker".
On MSDN, it states that the Event occurs when the user clicks the hyperlink. I can't seem to find anywhere that directly states whether this Event is triggered before or after the user is directed to the other sheet, though. If it gets triggered right after, that wouldn't really help me, but if it gets triggered before, I could put an Application.ScreenUpdates = False in the event, and it would solve my problem.
TL;DR (Get to the point already):
Does the Workbook_SheetFollowHyperlink Event happen before or after the user is directed to where ever the hyperlink is pointed?
To answer your question, the event is triggered after the hyperlink is followed. You can demonstrate this using the code below:
Private Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink)
Debug.Print "Workbook level: " & ActiveSheet.Name
End Sub
When the event is triggered, the ActiveSheet is the sheet directed to by the hyperlink.
I'm not sure of a way to solve your problem directly, even the Click() event won't be raised when you click a hyperlink. However, the Worksheet level hyperlink event handler will be called before the Workbook level handler and this may speed the process up enough to not see the flicker.
You can prove this if you leave the Workbook level event as is and add the following code to the Worksheet containing the hyperlinks:
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
Debug.Print "Worksheet level: " & ActiveSheet.Name
Sleep 1000
Debug.Print "Leaving worksheet level event"
End Sub
After a few experiments (see below) I concluded that:
Allow the user to use the hyperlink columns when macros are disabled.
When macros are enabled, hide the current hyperlink column and show another column that gives the user a different "hyperlink" that takes them directly to where you want them to go.
The 2nd hyperlink can easily be "simulated" such that it picks up the other columns hyperlink. (See below)
I hope his helps
Interesting, here's a few things I tried
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
' This does not fire if the user clicks directly on the hyperlink text
' it only fires if when click on the cell space that is not text
With ActiveCell
If Hyperlinks.Count Then
MsgBox "hi" & .Hyperlinks(1).Range
.Hyperlinks(1).Follow
End If
End With
End Sub
However you could make the text in the cells look like a hyperlink but actually just be blue underlined text. You could then use the Worksheet_SelectionChange to go to a related cell.
The question then become how to store the related cell.
You want to store it so that if row and column are inserted on the destination sheet, the reference will adjust. (eg NOT in comments, or the description of named ranges etc..)
Depending on how much data you have there's a variety of ways you could choose from.
I think I would favour this:
Having a hidden column next to the cell on display that has a hyperlink. The cell on display has a formula that is set to pick up the value from the hidden column (I quite like the sound of this as you have the hyperlink column already - so just modify the above code to get the hyperlink from the column next to the clicked cell using offset perhaps)
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
' This does not fire if the user clicks directly on the hyperlink text
With ActiveCell.offset(0,1)
If Hyperlinks.Count Then
.Hyperlinks(1).Follow
End If
End With
End Sub
You could mess around with named ranges, but it will be a pain.
I've just realised that what I tried won't help much as you need the hyperlink to work when macros have not been enabled!
So to get the above to work you could change the columns displayed when the user enables macros. ie the hyperlink column is shown when macros are disabled (and the column to the left of it is not).
When macros are enabled hide the hyperlink column and show the one to the left of it that will cause the SelectionChange event to run.
(You need to beware how other hyperlinks are used as any cell with a hyperlink next to it will respond to the event. You may need to use intersection to check the cell clicked is in a namedrange that contains "all the cells that need to respond to a user clicking them in the manner".
All the above sounds a bit mad, but it would appear the event model does not facilitate stopping the screen flickering.
I hope there is a better way of doing what you want, but for what it's worth, the above might help.
Harvey

Access 2010 Me.Refresh/Me.Requery

I have a form that I want refreshed when the submit button is clicked. Preferably those that have default values will be restored and those without will be blank.
The submit button has an attached OnClick Macro that, checks to make sure all fields are filled, if so an action query runs that inserts a new row into a table.
So its after this action query that I want the refresh to occur. I have tried researching and come across suggestions that suggest using VBA code Me.Requery or Me.Refresh. I'm not 100% on how to incorporate this into the macro. The RunCode command doesn't recognize the function I put the code in, and The convert macro to VBA option in the top left is grey'd out.
I'm new to Access and just not seeing where the communications are for code and macros if someone could please elaborate for me I would be greatly appreciated.
Please consider my solution as a brief introduction to VBA. If you care to learn the language, you will find there is very little you cannot do.
Within your submit button properties, there should be an 'Event' tab. In this tab, the On Click should be set to [Event Procedure]. Click the three dot button just to the right of that, and it will launch the VBA editor.
All you need to have here between the Private Sub and End Sub lines are these lines of code:
DoCmd.RunMacro ("Mac_1")
Me.TextBox1.Value = "Null"
Me.CombBox1.Value = "Null"
Me.Refresh
MsgBox "Your Save Was Successful.", vbOKOnly, "Saved"
"Mac_1" is the name of the macro you want to execute. the ME.Refresh executes as soon as mac_1 finishes, and will refresh the page. Be sure to enclose it in a proper quote (") and not a double tick ('').
The Requery command can be used from both within VBA code or a macro. It sounds like you are using the macro designer so you can use the Requery macro action instead of VBA.
Just add this to your macro after you have inserted your new data.
This macro action lets you specify a control to requery. The parameter can be left blank to requery the source of the active object. More information can be found here.
Edit
In response to your comments, I think you should try experimenting with the SetProperty macro action (more details here).
I have attached this macro to a button click event and the value from the TextBox called txtInputValue is cleared. The Value field is left blank as you want to fully remove the value from the text box.

Gray out a form row's (detail's) button conditionally with VBA code

I have a standard form in MS-Access which lists a bunch of orders, and each row contains order no, customer, etc fields + a button to view notes and attached document files.
On request from our customer we should gray out the button btnAnm (or check or uncheck a checkbox) depending on a calculation from two queries to two other tables (a SELECT COUNT WHERE and a check if a text field is empty).
I've tried btnAnm_BeforeUpdate(...) and btnAnm_BeforeRender(...) and put breakpoints in the subs, but none of them trigger. The same if I use the control Ordernr instead of btnAnm.
I'd like a function in the Detail VBA code to be triggered for each "Me." (row) so to speak, and set the row's control's properties in that sub.
What do I do? I've looked at the help file and searched here.
*Edit: So I want to do something that "isn't made to work that way"? Ie. events are not triggered in Details.
As an alternative, could I base the value of a checkbox on each line on a query based on the 'Ordernr' field of the current row and the result of a SELECT COUNT from another table and empty field check?
Do I do this in the query the list is based on, or can I bind the extra checkbox field to a query?
A description of how to do this (combine a COUNT and a WHERE "not empty" to yes/no checkbox value) would be perfectly acceptable, I think! :)*
You cannot do much with an unbound control in a continuous form, anything you do will only apply to the current record. You can use a bound control with a click event so that it acts like a button.
Presumably the related documents have a reference to the order number that appears on your form, which means that you can create a control, let us call it CountOrders, with a ControlSource like so:
=DCount("OrderID","QueryName","OrderID=" & [OrderID])
The control can be hidden, or you can set it up to return true or False for use with a textbox, you can also use it for Conditional Formatting, but sadly, not for command buttons.
Expression Is [CountOrders]>0
You can also hide the contents and add a click event so that is acts in place of the command button. Conditional Formatting will allow you to enable or disable a textbox.
As I understand your question, you have a continuous form with as command button that appears on each row - and you'd like to enable/disable the button conditionally depending on the contents of the row.
Unfortunately you can't do that. It seems that you can't reference the individual command buttons separately.
Having wanted to do something similar in the past I came up with two alternate ways of setting up my interface.
Put a trap into the onClick code for the Button. Which is icky, because it is counter intuitive to the user. But it gets you that functionality now.
Move the command button (and editable fields) up into the form header, and make the rows read only. Your users then interact with the record only in the header, and select the record they want work with in the list below. As I recall this is known a Master-Detail interface.