gpt4 book ai didi

vba - Dim As New vs Dim/Set 有什么区别

转载 作者:行者123 更新时间:2023-12-04 02:45:06 25 4
gpt4 key购买 nike

在 VBA 中,我可以通过以下两种方式之一创建对象:

'First way
Dim myCol1 As New Collection

'Second way
Dim myCol2 As Collection
Set myCol2 = New Collection

myCol1.Add "AAA" 'Works
myCol2.Add "BBB" 'Works as well

第二种方式只是第一种方式的更详细版本,还是 myCol1 和 myCol2 对象之间实际上存在差异?

最佳答案

有几个关键区别。你绝对应该更喜欢第二个 Dim/Set方法。

原因 1 - 与 As New ,在调用该对象的属性或方法之前不会创建该对象,但请查看此示例,其中将对象设置为 Nothing,然后调用属性/方法会导致对象重新实例化自身:

Sub ShortcutInstantiation()

Dim x As New Collection

x.Add "FOO", "BAR"
Set x = Nothing

'This line implicitly recreates a new Collection
Debug.Print x.Count

Debug.Print x Is Nothing 'Prints False

End Sub

Sub SafeInstantiation()

Dim x As Collection
Set x = New Collection

x.Add "FOO", "BAR"
Set x = Nothing

'Throws error because x is nothing
Debug.Print x.Count

End Sub

原因 2 As New方法较慢,因为 VBA 需要在每个属性或方法调用之前检查它是否已实例化对象。

看看这个伪代码,看看 VBA 在幕后做了什么:
Sub NotSoShortcutInstantiation()

Dim x As New Collection

If x Is Nothing Then Set x = New Collection
x.Add "FOO", "BAR"

If x Is Nothing Then Set x = New Collection
x.Add "FIZZ", "BUZZ"

If x Is Nothing Then Set x = New Collection
x.Add "CAR", "DOOR"

If x Is Nothing Then Set x = New Collection
Debug.Print x.Count

End Sub

原因 3 如果对象构造函数在预期之后执行某些操作,而不是在显式实例化它时执行某些操作,则可能存在严重的时序差异:

比较这段代码的结果:
Sub InstantiationTiming()

Dim foo As String

Dim x As New Class1
Debug.Print Format(Now(), "hh:mm:ss") & " x should be ready"
foo = x.foo

Dim y As Class1
Set y = New Class1
Debug.Print Format(Now(), "hh:mm:ss") & " y should be ready"
foo = y.foo

End Sub
As New方法打印:
06:36:57 x should be ready
06:36:57 Class Initialized
Set y = New方法打印:
06:36:57 Class Initialized
06:36:57 y should be ready

关于vba - Dim As New vs Dim/Set 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42656468/

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