运行时添加的控件如何实现消息处理?
各位大虾:俺用VBA写了一个Excel的应用程序,其中有一个UserForm中,根据所打开文件的不同,在运行时随机添加了若干个控件,请问俺应该如何对这些运行时添加控件的消息进行处理,如何添加这类控件的消息处理函数?
本来发到Office VBA专区了,但是没人回答,这里的高手能否提点一二?现行谢过。
[解决办法]
在VB中是如样处理的:
Option Explicit
'声明对象变量为 CommandButton 。
Private WithEvents cmdObject As CommandButton
Private Sub Form_Load()
Set cmdObject = Form1.Controls.Add( "VB.CommandButton ", "cmdOne ")
cmdObject.Visible = True
cmdObject.Caption = "Dynamic CommandButton "
End Sub
Private Sub cmdObject_Click()
Print "This is a dynamically added control "
End Sub
但不是VBA是否有不同,试试吧
[解决办法]
把 VB 标准控件(VB自带的控件)跟 ActiveX 控件分开处理。实现方法比较苯,代码量较大,估计全部写完得几千行左右,但绝对通用。
以下代码在类 ControlExtender 中
Option Explicit
' 事件声明需要自己扩充,这里只是一个示例,可参考 VBControlExtender 对象的 ObjectEvent 事件
Public Event ObjectEvent(ByVal EventName As String)
' VB 标准控件
Private WithEvents mCmd As CommandButton
Private WithEvents mTxt As TextBox
'...
' ActiveX 控件
Private WithEvents mExtender As VBControlExtender
' 处理传入控件的事件
Public Sub Attach(ByVal Ctr As Control)
Select Case UCase(TypeName(Ctr))
Case UCase( "CommandButton ")
Set mCmd = Ctr
Case UCase( "TextBox ")
Set mTxt = Ctr
Case UCase( "PictureBox ")
'...
Case Else
Set mExtender = Ctr
End Select
End Sub
Private Sub mCmd_Click()
RaiseEvent ObjectEvent( "Click ")
End Sub
Private Sub mExtender_ObjectEvent(Info As EventInfo)
RaiseEvent ObjectEvent(Info.Name)
End Sub
Private Sub mTxt_Change()
RaiseEvent ObjectEvent( "Change ")
End Sub
Private Sub mTxt_Click()
RaiseEvent ObjectEvent( "Click ")
End Sub
' ...
以下代码在窗体 Form1 中
Private WithEvents mControlExtender As ControlExtender
Private Sub Command1_Click()
Dim Ctr As Control
If mControlExtender Is Nothing Then Set mControlExtender = New Class1
Set Ctr = Controls.Add( "VB.CommandButton ", "cmd ")
Ctr.Move 1000, 1000, 2000, 2000
Ctr.Visible = True
mControlExtender.Attach Ctr
End Sub
Private Sub mControlExtender_ObjectEvent(ByVal EventName As String)
MsgBox EventName
End Sub
如果要处理多个控件,建立一个基于 ControlExtender 的集合类。