How to properly create an Object from a Custom Class? (Set myObj = ?)

Answered How to properly create an Object from a Custom Class? (Set myObj = ?)

  • Tuesday, March 06, 2012 1:59 PM
     
     

    - Given a custom Class... in Class Modules... named mathClass
    - I've made the code below work without the "Set" statement but...
    - Isn't it proper use to first Declare the new Object (instance of the Class)
    - AND... then use the "Set Statement" to initalize the object?
    - And if so, then what would you "set" matObj below equal to?

    Dim mathObj As New mathClass
    'Set mathObj = ???
    mathObj.FirstNum = "35"
    mathObj.SecondNum = "25"
    lngResult = xyzObj.Add
    Dim mathObj = Nothing

    Thanks for any help.

All Replies

  • Tuesday, March 06, 2012 2:33 PM
    Moderator
     
     

    If you use Dim...New there's no need to use Set...New (or CreateObject) to create the object, though no harm to include it for clarity.

    In theory it's less efficient to use New as each time you refer to the object, internally a check will be made to ensure it exists. In practice it's unlikely you'd notice unless referring to the object a very large number of times.

    Use of Dim...New is more a matter of style, though personally I almost never use it and explicitly create the object as needed.

    Peter Thornton

  • Tuesday, March 06, 2012 3:03 PM
     
     

    Peter...

    Can you give me a simple code snippet of how you "explicitly create the object as needed" ... as opposed to using Dim...Net... or whatever.

    Thanks for the help.

     

  • Tuesday, March 06, 2012 3:34 PM
    Moderator
     
     Answered

    You'd normally want to use Dim and fully declare to use "Early Binding" (which you'd have to do with a VBA class object though not necessarily with registered Com objects), or Dim...As Object if "Late Binding".

    So with your VBA class object example

    Dim mathObj As mathClass
    Set mathObj = New mathClass
    ' and the rest as per your example

    In passing it's normally not necessary to explicitly destroy the object with Set ...Nothing if the only reference to it is about to go out of scope, which it will do naturally and efficiently at the end of the routine in which it was declared.

    Peter Thornton

  • Tuesday, March 06, 2012 8:29 PM
     
     

    That is what I was looking for.

    And, your right about Set...Nothing.

    Thanks Peter!