允许命令按钮在单击时获得焦点

以下示例使用 TakeFocusOnClick 属性控制 CommandButton 在用户单击焦点时是否接收焦点。 The user clicks a control other than CommandButton1 and then clicks CommandButton1. If TakeFocusOnClick is True, CommandButton1 receives the focus after it is clicked. 用户可以通过单击 ToggleButton 更改 TakeFocusOnClick 的值。

若要使用本示例,请将此示例代码复制到窗体的"脚本编辑器"中。 若要运行本代码,需要打开该窗体,以便激活 Open 事件。 确保该窗体包含:

  • 一个名为"CommandButton1"的 CommandButton

  • 一个名为"ToggleButton1"的 ToggleButton

  • 一个或两个其他控件,如 OptionButtonListBox

Sub CommandButton1_Click() 
 MsgBox "Watch CommandButton1 to see if it takes the focus." 
End Sub 
 
Sub ToggleButton1_Click() 
 Set ToggleButton1 = Item.GetInspector.ModifiedFormPages("P.2").Controls("ToggleButton1") 
 Set CommandButton1 = Item.GetInspector.ModifiedFormPages("P.2").Controls("CommandButton1") 
 
 If ToggleButton1 = True Then 
 CommandButton1.TakeFocusOnClick = True 
 ToggleButton1.Caption = "TakeFocusOnClick On" 
 Else 
 CommandButton1.TakeFocusOnClick = False 
 ToggleButton1.Caption = "TakeFocusOnClick Off" 
 End If 
End Sub 
 
Sub Item_Open() 
 Set ToggleButton1 = Item.GetInspector.ModifiedFormPages("P.2").Controls("ToggleButton1") 
 Set CommandButton1 = Item.GetInspector.ModifiedFormPages("P.2").Controls("CommandButton1") 
 
 CommandButton1.Caption = "Show Message" 
 
 ToggleButton1.Caption = "TakeFocusOnClick On" 
 ToggleButton1.Value = True 
 ToggleButton1.Width = 90 
End Sub

支持和反馈

有关于 Office VBA 或本文档的疑问或反馈? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。