问题
I have a template document which contains several sections and a few tables. The thing is, I'm trying to insert a drop-down list inside on of the cells in the table. And for a drop-down list to work, the document needs to be protected. But if I protect the entire section the table is in, the entire table is protected.
So, I was wondering if there's a way of executing a macro code IF the user clicks on the drop-down list? The code would then protect the document, making the control actually work, then select a choice and when the user clicks outside of the field, the document should get unprotected.
Is this possible?
回答1:
There is actually a WindowSelectionChange event in Word VBA that you can use. It is described in the Word VBA help file under "Using Events with the Application Object".
The trick is to assign your application to a variable in a class module (I've named mine EventClassModule) using the WithEvents keyword:
Public WithEvents App As Word.Application
Then in your ordinary Document Open event, you can initialize the variable to 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's a little finicky (the oEvents object has a tendency to become uninitialized for some reason), but hopefully this will be a start for your solution.
回答2:
Rather than use a drop-down box from the forms toolbar, you could use a ComboBox from the control toolbar. Then you could use the ComboBox click event. You could also attach code to the GotFocus/LostFocus event for when the user clicks outside of the ComboBox.
来源:https://stackoverflow.com/questions/1043307/word-vba-if-cursor-is-in-cell-bookmark-run-code