在 VBA 中初始化对象的正确方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9970322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the correct way to initialize objects in VBA?
提问by ferics2
I have a custom object that I was adding to an array via a loop. The problem was when I initialized the object like this:
我有一个自定义对象,我通过循环将其添加到数组中。问题是当我像这样初始化对象时:
Dim CallNum As New Lib_CallNum
The last object added in the loop would overwrite all the other objects added during the loop. So I would end up with an array filled with a bunch of the same objects. To fix this I had to change the way I was initializing the object to:
循环中添加的最后一个对象将覆盖循环期间添加的所有其他对象。所以我最终会得到一个充满一堆相同对象的数组。为了解决这个问题,我必须将初始化对象的方式更改为:
Dim CallNum As Lib_CallNum
Set CallNum = New Lib_CallNum
But I am unsure why the first initialization would not work. So what is the difference between the two sets of code?
但我不确定为什么第一次初始化不起作用。那么这两组代码有什么区别呢?
回答by chris neilsen
The Dim
inside a loop is not actually executed on each iteration. It is only executed the first time the variable is encountered.
在Dim
一个循环中实际上并没有在每次迭代执行。它仅在第一次遇到变量时执行。
To demonstrate this, add a section to your Lib_CallNum
class initialisation definition:
为了证明这一点,在你的Lib_CallNum
类初始化定义中添加一个部分:
Private Sub Class_Initialize()
Debug.Print "Initialise Lib_CallNum"
' ...
End Sub
and run your original code. Initialise will only be reported once. From then on you are adding the same instance to the array many times.
并运行您的原始代码。初始化只会被报告一次。从那时起,您将多次向数组添加相同的实例。
The correct way to initialise new instances objects is as @Doug has told you, Set ... = New ...
初始化新实例对象的正确方法是@Doug 告诉你的, Set ... = New ...
回答by Doug Glancy
From my experience on your previous post, I still don't think you've got quite the right approach, although not sure since never saw your finished code. You should have something like:
根据我在您之前的帖子中的经验,我仍然认为您没有找到正确的方法,尽管不确定,因为从未见过您完成的代码。你应该有类似的东西:
Function Something
Dim CallNum as Lib_CallNum
...
Do While SomeCondition
Set CallNum = New Lib_CallNum
'do some stuff
Set CallNum = Nothing
Loop
Return Whatever
End Function
In other words, you should declare the object at the top of the function - not repeatedly in the loop - and instantiate (and set it to Nothing) in the loop.
换句话说,您应该在函数的顶部声明对象——不要在循环中重复——并在循环中实例化(并将其设置为 Nothing)。
If you google you can find explanations of why not to instantiate an object in its declaration. Professional Excel Development has a good one. But I think your problem might have been in never setting it to Nothing. Not sure though.
如果您使用谷歌搜索,您可以找到有关为什么不在其声明中实例化对象的解释。Professional Excel Development有一个很好的。但我认为您的问题可能是从未将其设置为 Nothing。虽然不确定。