Change 事件
优质
小牛编辑
129浏览
2023-12-01
该事件发生于最终用户改变命令栏组合框中的选项时。
Private Sub CommandBarComboBox_Change
(ByVal Ctrl As CommandBarComboBox)
说明
Change 事件由CommandBarComboBox 对象识别。若要返回某个 CommandBarComboBox 控件的Change 事件,请用关键词WithEvents 声明一个变量,并将其值设置为该CommandBarComboBox 控件。当触发Change 事件时,将执行该控件的OnAction 属性所指定的宏或代码。
示例
以下示例创建一个包含CommandBarComboBox 控件的命令栏,该控件包含四个选项。该组合框通过 CommandBarComboBox_Change 事件响应用户操作。
Private ctlComboBoxHandler As New ComboBoxHandler
Sub AddComboBox()
Set HostApp = Application
Dim newBar As Office.CommandBar
Set newBar = HostApp.CommandBars.Add(Name:="Test CommandBar", Temporary:=True)
Dim newCombo As Office.CommandBarComboBox
Set newCombo = newBar.Controls.Add(msoControlComboBox)
With newCombo
.AddItem "First Class", 1
.AddItem "Business Class", 2
.AddItem "Coach Class", 3
.AddItem "Standby", 4
.DropDownLines = 5
.DropDownWidth = 75
.ListHeaderCount = 0
End With
ctlComboBoxHandler.SyncBox newCombo
newBar.Visible = True
End Sub
上述示例使用以下代码,此段代码保存在 VBA 工程的类模块中。
Private WithEvents ComboBoxEvent As Office.CommandBarComboBox
Public Sub SyncBox(box As Office.CommandBarComboBox)
Set ComboBoxEvent = box
If Not box Is Nothing Then
MsgBox "Synced " & box.Caption & " ComboBox events."
End If
End Sub
Private Sub Class_Terminate()
Set ComboBoxEvent = Nothing
End Sub
Private Sub ComboBoxEvent_Change(ByVal Ctrl As Office.CommandBarComboBox)
Dim stComboText As String
stComboText = Ctrl.Text
Select Case stComboText
Case "First Class"
FirstClass
Case "Business Class"
BusinessClass
Case "Coach Class"
CoachClass
Case "Standby"
Standby
End Select
End Sub
Private Sub FirstClass()
MsgBox "You selected First Class reservations"
End Sub
Private Sub BusinessClass()
MsgBox "You selected Business Class reservations"
End Sub
Private Sub CoachClass()
MsgBox "You selected Coach Class reservations"
End Sub
Private Sub Standby()
MsgBox "You chose to fly standby"
End Sub