excel vba 中的动态列表视图控件

问题描述 投票:0回答:2

有人愿意分享为运行时创建的列表视图控件创建单击事件处理程序所需的代码吗? 我可以创建列表视图控件并填充它,但不知道如何在用户窗体中创建类模块和关联代码来处理事件。

listview dynamic
2个回答
1
投票

如果您在运行时创建并填充了控件,则可以只处理控件的事件,而无需创建类模块。

有一个与动态添加控件相关的更普遍的问题,您可以在here找到。

但是这是我专门为 ListView 控件编写的一个示例。 请注意,您需要声明控件 WithEvents 才能使事件处理程序正常工作。 “AS”类型应该是您当前创建 ListView 时使用的类型。

Option Explicit
' Declare object variable as ListView and handle the events.'
Private WithEvents ListView1 As MSComctlLib.ListView 

Private Sub Form_Load()
   'Add button control and keep a reference in the WithEvents variable'
   Set ListView1 = Form1.Controls.Add("MSComctlLib.ListView", "ListView1")
   ListView1.Visible = True
   'Set other properties that need to be set for ListView1 here...'
End Sub

'Handle the events of the dynamically-added control'
Private Sub ListView1_ItemClick(ByVal Item As MSComctlLib.ListItem)
    Print "ItemClick Event fired from ListView1"
    Text1.Text = "Selected item: " & ListView1.SelectedItem.Text & ", with index: " & ListView1.SelectedItem.Index
End Sub

如果您的项目中没有控件实际库的引用,您可以尝试以下操作:

Option Explicit
Dim WithEvents objExt As VBControlExtender ' Declare VBControlExtender variable

Private Sub LoadControl()
   'Here you need to add the license to the control's library, in this case if you have VB6 installed you should be covered
   'Licenses.Add "MSComctlLib.ListView", "xydsfasfjewfe"
   'Here replace with correct library.control name
   Set objExt = Controls.Add("MSComctlLib.ListView", "objExt")
   objExt.Visible = True 
   'Set other properties here...
End Sub

Private Sub objExt_ObjectEvent(Info As EventInfo)
   ' Program the events of the control using Select Case.
   Select Case Info.Name
   Case "Click"
      ' Handle Click event here.
   ' Other cases now shown
   Case Else ' Unknown Event
      ' Handle unknown events here.
   End Select
End Sub

请参阅与上述相关的 MSD 文章此处

稍后再聊。

PS:如果您仍想为控件创建包装类,请参阅此处带有触发事件的接口的类的示例。


0
投票

下午好,我需要撤消用ListView.ListItems.ListsubIten.FormsControl.Add("Frame.1".....)方法添加的动态控件,我想知道代码,谢谢

© www.soinside.com 2019 - 2024. All rights reserved.