我想在打开工作簿或单击不同工作簿中的单元格时更新组合框/文本框。 我开始想要将函数传递给类来执行。因为这看起来是最合理的方式。 VBA 真的让我很困惑。
为什么? 我正在使用 GUI 编写一个宏,需要打开一个信息工作簿 (Info-WB) 来汇总另一个工作簿 (S-WB) 中选定的工作表范围。我想实时显示 Info-WB 是否打开,然后 GUI 元素应该像使用移液器工具一样对 S-WB 中选择工作表(及其中的单元格)做出反应。
我读到了这似乎是一个解决方案,但我不太明白: https://stackoverflow.com/questions/53123046/implementing-a-change-event-to-check-for-changes-to-textbox-values-and-enabling
我想这就是我需要的: https://stackoverflow.com/questions/19860901/update-form-with-events https://bettersolutions.com/vba/events/excel-application-level-events.htm 我知道我需要将事件粘合到一个类上:
Public WithEvents oProgressFormClassInstance As clsProgressForm
'The WithEvents here implies that whenever the specific object referenced by this variable
'throws an event, it will trigger the event handler for that event in this class (form)
但是当我使用 IDE 构建菜单时,如何实际使用带有事件的类,就像 VBA 为我创建的类一样?
我还在这个网站上发现了一个问题,指出我在具有事件处理程序的类中使用 Application.Run 。 所以最后我正在考虑将 UI 元素和函数名称保存为该类中的变量,并以这种方式将其传递给事件。但我学习编程的方式(使用 lua)似乎太混乱和hacky了。
更新类:
Public WithEvents appevent As Application
'Implements ComboBox '...one can dream
Public funtionName As String
Public uiElement As Variant
Private Sub appevent_WorkbookOpen(ByVal Wb As Workbook)
Application.Run updateSomeIUStuff
End Sub
Private Sub Class_Initialize()
Set Me.appevent = Application
End Sub
编辑:将“设置”添加到“Me.appevent = Application”
用户表单中的代码:
Private Sub UserForm_Initialize()
Dim uUpdater As Variant
Set uUpdater = New updater
End Sub
Sub updateSomeIUStuff()
MsgBox "If Mommy's Purse Didn't Belong In The Microwave, Why Did It Fit?"
'ComboBox.doStuff()
End Sub
现在由于某种原因 VBA 说:对象变量或 With-block-variable 未定义 并向我指出“Me.appevent = Application”
除了不起作用之外,这对我来说看起来是错误的。为什么微软要这样对我?
这是
UserForm1
内的代码。我向 UI 添加了一个文本框 (TextBox1
)。侦听器或在您的情况下 uUpdater 是 UserForm1 的成员/字段。在 UserForm1 的 Initialize 子项中,您只需实例化侦听器/uUpdater。
Private listener As EventListener
Private Sub UserForm_Initialize()
Set listener = New EventListener
End Sub
Public Sub UpdateSomeStuff()
MsgBox "Some Info"
End Sub
这是
EventListener
里面的代码。您不需要使用Application.Run
。您可以简单地调用该函数,如我的示例所示。
Public WithEvents appevent As Application
Private Sub appevent_WorkbookOpen(ByVal Wb As Workbook)
UserForm1.UpdateSomeStuff
End Sub
Private Sub Class_Initialize()
Set appevent = Application
End Sub