Y.G.J
Y.G.J

Reputation: 1108

Check if object is set in VBScript

Assume I create an object:

set newcon = Server.CreateObject("ADODB.Connection")

And at some point I destroy it:

set newcon = nothing

How can I tell if newcon is an object or nothing?

I have tried:

newcon is nothing

but I get object required.

If I try isobject or isnull or isempty it doesn't return either true or false.

Is there something else that really works?

Upvotes: 5

Views: 19558

Answers (3)

Rohit Borse
Rohit Borse

Reputation: 21

You will get an error Object required if your code resembles like

Dim Obj
MsgBox Obj Is Nothing

Here, in the above code you have not initialized Obj with any object and if you are trying to destroy an object which is not existing or initialized then obviously you will get an error "Object required" to destroy that object.

Now try below

Dim Obj
Set Obj = CreateObject("Excel.Application") 'Creating an object
MsgBox Obj Is Nothing 'Returns False
Set Obj = Nothing 'Destroying an object
MsgBox Obj Is Nothing 'Returns True

What we have done in the above code, We have created an object using Set Obj = CreateObject("Excel.Application") statement. Then we are verifying if object we have created is existing or not using MsgBox Obj Is Nothing statement. This returns 'True' as object is existing. Now as requirement arose, we are going to disassociate i.e. destroying an object using statement Set Obj = Nothing. In the last statement MsgBox Obj Is Nothing we are again verifying, if an object Obj is disassociated i.e. destroyed or not.

Upvotes: 2

seeker
seeker

Reputation: 316

I see this is old question, however, posted answers are correct but incomplete, therefore I will post my way:

Dim Obj
Set Obj = CreateObject("ADODB.Connection")
If IsObject(Obj) Then
    If Not Obj Is Nothing Then
        Set Obj = Nothing
    End If
End If
WScript.Echo "Is Nothing: " & (Obj Is Nothing)

Upvotes: 0

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38755

I believe you accidentially changed newcon before testing it with Is Nothing:

>> set newcon = CreateObject("ADODB.Connection")
>> WScript.Echo 0, IsObject(newcon)
>>
0 -1
>> set newcon = Nothing
>> WScript.Echo 1, IsObject(newcon)
>>
1 -1
>> WScript.Echo 2, newcon Is Nothing
>>
2 -1
>> newcon = "oops"
>> WScript.Echo 3, newcon Is Nothing
>>
Error Number:       424
Error Description:  Object required
>> WScript.Echo 4, newconn Is Nothing ' oops
>>
Error Number:       424
Error Description:  Object required

If you get Error 434, then newcon (or the variable you really test) doesn't hold an object or Nothing.

Upvotes: 1

Related Questions