Word vba - if the cursor is in a cell / bookmark - start code

I have a template document that contains several sections and several tables. The fact is that I'm trying to insert a drop-down list inside the cells in the table. And for the drop-down list, the document must be protected. But if I protect the entire partition in which the table is located, the entire table is protected.

So, I was wondering if there is a way to execute the macro if the user clicks on the drop-down list? Then the code will protect the document by making the control actually executed, then select the choice, and when the user clicks outside the field, the document should be insecure.

Is it possible?

+4
source share
2 answers

There is a WindowSelectionChange event in Word VBA that you can use. It is described in the Word VBA help file in the "Using Events with the Application Object" section.

The trick is to assign your application a variable in the class module (I named my EventClassModule) using the WithEvents keyword:

Public WithEvents App As Word.Application 

Then in your normal document open event, you can initialize the variable in the current application:

 Dim oEvents As New EventClassModule Private Sub Document_Open() Set oEvents.App = Word.Application End Sub 

Back in the EventClassModule, you use the WindowSelectionChange event to check if the selection is a table:

 Private Sub App_WindowSelectionChange(ByVal Sel As Selection) If Sel.Information(wdWithInTable) And ThisDocument.ProtectionType = wdNoProtection Then ThisDocument.Protect wdAllowOnlyFormFields ElseIf ThisDocument.ProtectionType <> wdNoProtection Then ThisDocument.Unprotect End If End Sub 

This code will be called whenever the cursor changes location. I tested it and it is a bit fictitious (the oEvents object tends to become uninitialized for some reason), but hopefully this will be the beginning for your solution.

+5
source

Instead of using the drop-down list on the form toolbar, you can use the ComboBox from the control toolbar. Then you can use the ComboBox click event. You can also attach code to the GotFocus / LostFocus event when the user clicks outside of the ComboBox.

0
source

Source: https://habr.com/ru/post/1286742/


All Articles