gpt4 book ai didi

vba - 自定义事件未触发

转载 作者:行者123 更新时间:2023-12-01 18:34:57 25 4
gpt4 key购买 nike

我使用的是 Excel 2010,在处理自定义事件时似乎出现了奇怪且意外的行为。

我 99% 确信这种方法几年前对我有用(也许是在 Excel 03/07 中 - 不记得了) < em>也许我只是搞砸了一些事情...

这是一个重现:

添加一个新的类模块并将其命名为Factory

Public Event AfterInitialize()

Private Sub Class_Initialize()
RaiseEvent AfterInitialize
End Sub

添加另一个类模块,名称为FactoryTest

Private WithEvents cFactory As Factory

Private Sub Class_Initialize()
Set cFactory = New Factory
End Sub

Private Sub cFactory_AfterInitialize()
Debug.Print "after inialized..."
End Sub

和一个标准的Module1并运行下面的

Sub Main()

Dim fTest As FactoryTest
Set fTest = New FactoryTest

End Sub

此时,我希望在立即窗口中看到初始化后..,但我没有...

单步执行代码似乎永远不会到达Private Sub cFactory_AfterInitialize()...

注意:

我可以将公共(public)子:RaiseAfterInitialize()添加到Factory类,然后在Initialize()事件中显式调用它FactoryTest 就像 cFactory.RaiseAfterInitialize() 这样,这可能是一个可能的解决方法,但我真正想要理解的是为什么它不能按照上面显示的原始方式工作?

There isn't much on VBA events on MSDN

谁能指出我做错了什么?

最佳答案

基于 VBA 语言规范部分 5.3.1.10 Lifecycle Handler Declarations ,我猜这就是原因(强调我的):

If a class defines a Class_Initialize lifecycle handler, that subroutine will be invoked as an method each time an instance of that class is created by the New operator, by referencing a variable that was declared with an <as-auto-object> and whose current value is Nothing, or by call the CreateObject function (section 6.1.2.8.1.4) of the VBA Standard Library. The target object of the invocation is the newly created object. The invocation occurs before a reference to the newly created object is returned from the operations that creates it.

所以就你的情况而言,在行中

Set cFactory = New Factory

Class_Initialize方法Factory在进行分配之前运行,这意味着在引发事件时,FactoryTest类实例不知道它。

<小时/>

更新

我通过向Factory添加一个方法对其进行了快速测试。它调用 Class_Initialize功能:

Public Sub test()
Class_Initialize
End Sub

然后添加对它的调用作为 FactoryTest.Class_Initialize 的一部分方法:

Private Sub Class_Initialize()
Set cFactory = New Factory
cFactory.test
End Sub

自从调用方法 test发生在 New Factory 之后已分配给cFactory ,“初始化后...”消息按预期显示。

关于vba - 自定义事件未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26589039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com