What's the difference between Dim As New vs Dim / Set

前端 未结 2 906
庸人自扰
庸人自扰 2020-11-29 09:31

In VBA, I can create objects one of two ways:

\'First way
Dim myCol1 As New Collection

\'Second way
Dim myCol2 As Col         


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 10:05

    The As New construct has legitimate uses. In a class, with a module level variable when you do not know which method will be called first then it saves some lines of code. So some code snippet I have lying around in a class is given here

    Option Explicit
    
    Private mdicQueryStringParams As New Scripting.Dictionary
    
    Function SafeItem(ByVal sKey As String, ByRef pvItem As Variant) As Boolean
    
        If mdicQueryStringParams.Exists(sKey) Then
            pvItem = mdicQueryStringParams.Item(sKey)
            SafeItem = True
        End If
    
    End Function
    

    Imagine very many more methods that rely upon an initialised mdicQueryStringParams. You'd have to write guard code to ensure that it was created in all of these methods.

    Now at this point you're saying but you can use Sub Class_Initialize to New up upon class creation. Like this

    Private Sub Class_Initialize()
        Set mdicQueryStringParams = New Scripting.Dictionary
    End Sub
    

    But suppose I want to recycle/reset part of the class's state then I could write a Clear method which sets mdicQueryStringParams to Nothing . In this case Sub Class_Initialise won't run again. Here on SO Mat's Mug has taught me that Static classes are possible in VBA (thanks!) so sometimes Sub Class_Initialise will only run once.

    (^ Admittedly I could set it to a New instance in the Clear method, yes, yes, I know, I know)

    The point is with the As New syntax you get a resurrecting variable as well as auto-initialisation. Surely as developers this is another technique/pattern in our toolbox that we should exploit and not ban.

    In truth, I use it infrequently but I just don't like banning stuff.

提交回复
热议问题