VBA控件常规使用--ToggleButton 切换按钮控件
2008-02-23 11:35:13| 分类: ExcelVBA |字号 订阅
切换按钮 控件具有相同外观作为一个 CommandButton 控件在您单击它。 当单击 切换按钮 控件, 它似乎按或推。 当未选中按钮 Value 属性的 切换按钮 控件是 True 选择按钮时, False 。 如果 TripleState 属性的值为 True , ToggleButton 控件还可以 Null 值。 可用似乎具有 Null 值 切换按钮 控件。
注意 On 值, 是 值, 和 True 值表明选定 ToggleButton 控件。 Off 值、 无 值, 和 False 值表明未选中 ToggleButton 控件。
如何获取 ToggleButton 控件的值要获取值 ToggleButton 控件, 请按照下列步骤操作:
1. |
启动 Excel, 并打开新空白工作簿。 |
2. |
在 工具 菜单, 指向 宏 , 然后单击 VisualBasic 编辑器 。 |
3. |
在 插入 菜单上, 单击要在工作簿中插入 UserForm UserForm 。 |
4. |
添加 UserForm 上一个 切换按钮 控件。 |
5. |
将 Label 控件添加到 UserForm。 |
6. |
双击要打开代码窗口为 ToggleButton 控件 切换按钮 控件。 |
7. |
在代码窗口, 为 ToggleButton1Click 事件键入下列代码: Private Sub ToggleButton1_Click()
If ToggleButton1.Value = True Then
' Set UserForm background to Red.
Me.BackColor = RGB(255, 0, 0)
Else
' Set UserForm background to Blue.
Me.BackColor = RGB(0, 0, 255)
End If
End Sub
|
8. |
在 运行 菜单上, 单击 运行子过程 / 用户窗体 。 | 当您单击 切换按钮 控件, 的 UserForm 更改背景色。
如何创建互斥 ToggleButton 控件组本示例将变量使用 MouseUp 事件并调用 ExclusiveToggleButtons 过程。 ExclusiveToggleButtons 过程决定 ToggleButton 控件, 选中, 然后取消其他。 若要创建互斥 ToggleButton 控件组, 请按照下列步骤:
1. |
启动 Excel, 并打开新空白工作簿。 |
2. |
在 工具 菜单, 指向 宏 , 然后单击 VisualBasic 编辑器 。 |
3. |
在 插入 菜单上, 单击 模块 。 |
4. |
在代码窗口为模块, 键入如下代码: ' Variable that holds the name of the ToggleButton that was clicked.
Public clicked As String
Sub ExclusiveToggleButtons()
Dim toggle As Control
' Loop through all the ToggleButtons on Frame1.
For Each toggle In UserForm1.Frame1.Controls
' If Name of ToggleButton matches name of ToggleButton
' that was clicked...
If toggle.Name = clicked Then
'...select the button.
toggle.Value = True
Else
'...otherwise clear the selection of the button.
toggle.Value = False
End If
Next
End Sub
|
5. |
在 插入 菜单上, 单击要在工作簿中插入 UserForm UserForm 。 |
6. |
将 Frame 控件添加到 UserForm。 |
7. |
Frame 控件中添加一个 切换按钮 控件。
重复此步骤向 Frame 控件中添加两个详细 切换按钮 控件。 |
8. |
双击以显示代码窗口对于 UserForm Frame 控件。 |
9. |
在代码窗口为模块, 为 ToggleButton MouseUp 事件键入下列代码: Private Sub ToggleButton1_MouseUp(ByVal Button As Integer, _
ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
clicked = ToggleButton1.Name
Application.OnTime Now, "ExclusiveToggleButtons"
End Sub
Private Sub ToggleButton2_MouseUp(ByVal Button As Integer, _
ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
clicked = ToggleButton2.Name
Application.OnTime Now, "ExclusiveToggleButtons"
End Sub
Private Sub ToggleButton3_MouseUp(ByVal Button As Integer, _
ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
clicked = ToggleButton3.Name
Application.OnTime Now, "ExclusiveToggleButtons"
End Sub
|
10. |
在 运行 菜单上, 单击 运行子过程 / 用户窗体 。 | 单击 切换按钮 控件, 时取消以前选定 切换按钮
|