Word vba - 如果光标在单元格/书签中 - 运行代码 [英] Word vba - if cursor is in cell / bookmark - run code
问题描述
我有一个包含几个部分和几个表格的模板文档.问题是,我试图在表格中的单元格内插入一个下拉列表.为了使下拉列表起作用,需要保护文档.但是如果我保护表所在的整个部分,整个表都会受到保护.
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.
这可能吗?
推荐答案
实际上,您可以使用 Word VBA 中的 WindowSelectionChange 事件.它在 Word VBA 帮助文件中的将事件与应用程序对象一起使用"下进行了描述.
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".
诀窍是使用 WithEvents 关键字将您的应用程序分配给类模块中的变量(我命名为我的 EventClassModule):
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
然后在你的普通 Document Open 事件中,你可以将变量初始化为当前的应用程序:
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
回到 EventClassModule,您使用 WindowSelectionChange 事件来检查所选内容是否为表格:
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
只要光标改变位置,就会调用此代码.我对其进行了测试,它有点挑剔(oEvents 对象由于某种原因倾向于未初始化),但希望这将成为您解决方案的开始.
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.
这篇关于Word vba - 如果光标在单元格/书签中 - 运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!