This is one of those often used functions in VB6 that could use a little improvement. The main problem with CreateObject is when it throws an error, it doesn’t report what object it was attempting to create at the time, which would be quite a handy thing to know.
Fortunately, CreateObject is one of small number of intrinsic functions in VB that can be overridden quite easily.
In other words, you can define your own CreateObject function, and VB will call your version instead of it’s built in version anywhere that you use it. This is quite handy because it means you can use the enhanced version without changing any calling code.
For instance, here’s a CreateObject function I put together that expands on the default error message string if it encounters a problem creating the object asked for. It simply adds in the PROGID of the object you’re trying to create.
Public Function CreateObject(ByVal Class$, Optional ByVal ServerName$) As Object '---- override the CreateObject ' function in order to register what ' object is being created in any error message ' that's generated Dim Source$, Descr$, ErrNum On Error Resume Next If Len(ServerName$) Then Set CreateObject = VBA.CreateObject(Class$, ServerName$) Else Set CreateObject = VBA.CreateObject(Class$) End If If VBA.Err Then Source$ = VBA.Err.Source Descr$ = VBA.Err.Description ErrNum = VBA.Err Descr$ = Descr$ & " (ProgID: " & Class$ If Len(ServerName$) Then Descr$ = Descr$ & ". Instantiated on Server '" & ServerName$ & "'" End If Descr$ = Descr$ & ")" On Error GoTo 0 VBA.Err.Raise ErrNum, Source$, Descr$ End If On Error GoTo 0 End Function
Put this function in a normal BAS module, and anywhere that you use CreateObject already, you’ll now be calling this function.
And to answer a few questions:
Q: Why do you use the VBA prefix for CreateObject and the ERR object in this piece of code?
A: In the case of CreateObject, you have to prefix it or this function would end up calling itself instead of the real VB CreateObject function.
In the case of the ERR object, see below.
Q: What other functions can be overridden?
I haven’t done an exhaustive study of it, but I can say that a particularly handy object to override is the built in VB ERR object defined in the VBA library.
Overriding that object allows you to extend error handling functionality in all sorts of ways.
For instance, you could add a LOG method to the ERR class, or a MSGBOX method that automatically formats an error for display in a message box.
But that’s a topic for another post.