Dim as New与Dim/Set有什么不同 [英] What's the difference between Dim As New vs Dim / Set

查看:32
本文介绍了Dim as New与Dim/Set有什么不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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,在调用该对象的属性或方法之前不会创建对象,但请看以下示例,其中将对象设置为空,然后调用属性/方法会导致对象重新实例化自身:

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

原因2As 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

这篇关于Dim as New与Dim/Set有什么不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆