first_page the funky knowledge base
personal notes from way, _way_ back and maybe today

VB: The Use of New Keyword, the CreateObject() and the GetObject() Functions

The New Keyword

Use the New keyword to create objects associated with a Type Library. In short, if the VB Object Browser can show your object's classes and members then this object is associated with a Type Library. So, for example, Excel.Application is a member of a Type Library. The New keyword can be used in this Declaration:

Private objExcel As Excel.Application

Later, in a Procedure, we use the New keyword for explicit object creation:

Set objExcel = New Excel.Application

The New keyword can be used in the Declaration (for implicit object creation) but this slows down VB at runtime as it has to check to see if objExcel is instantiated each time it is called. Moreover the statement

objExcel Is Nothing

will always be False since implicit object creation sets the object's variable to Nothing. For more information, please see MS KB article Q138072 ("INFO: Tips to Improve Performance While Using OLE servers").

The CreateObject() Function

The CreateObject() function has all of the functionality of the New keyword. But has two notable advantages: it creates objects without a Type Library (that VB understands) and it creates objects that can recognize and comply with COM. The latter is most important for scaling a VB solution into MTS. For more information, please see MS KB article Q202535 ("INFO: Use of New Keyword In MTS Environment").

The GetObject() Function

I have trouble trying to compare this function with the other two object-creating "things" because this function lies in the context of "persisted" objects. This means that GetObject() can create objects from files. For example:

Dim CADObject As Object
Set CADObject = GetObject("C:\\CAD\\SCHEMA.CAD")

I don't use GetObject() as of this writing. The opinion here is that this function is used in OLE Automation of Microsoft Office Applications and other desktop applications based on VBA. I daresay that GetObject() is "heavier" than CreateObject() and packs quite a performance hit (relatively speaking). Nevertheless, I feel that it is important to mention that there is a difference between GetObject() and GetObject(""). This may come in handy someday. For more information please see MS KB article Q114347 ("INFO: OLE Automation Objects with GetObject and CreateObject").

mod date: 2000-02-09T03:59:50.000Z