set Object = Nothing

A

Ardus Petus

I see quite often Excel Sub's with following code

Sub mySub()
Dim myObject as Object
set myObject = CreateObject("www.xx")
...
(some code)
...
set myObject = Nothing
end Sub

What is the use of setting a local variable to Nothing, as it will be
destryed by End Sub ?

Cheers,
 
P

Peter T

In your particular example I do not believe there is any need to explicitly
destroy the object. As you say it will go out of scope when the routine
terminates.

Regards,
Peter T
 
M

ML0940

Actually, when you declare a variable, you are basically reserving a chunk
of memory in your computer to store that variable (read about Data Types) so
by setting it to nothing, you may be freeing that memory (resources) up on
your computer

Also, by setting the variable to Nothing, you are letting go on the
connection to the object that you set the variable to; especially in this
case to where it is not an intrinsic Excel object but rather a external
object.

So, espeically in this case, I def. say it is a very good idea.

Suppose your macro crashes prior to getting to the End Sub?

It is never a bad practice to let go of objects when you are done with them
but there can be some problems on occasion, if you do not.

There are also occasions to where I will set a string variable to "" when
done with it. That depends on the case and need but with external conections,
I would say ALWAYS set it free when done with it; otherwise a real crash can
take place

Hope this helps a bit

ML
 
R

RB Smissaert

Suppose your macro crashes prior to getting to the End Sub?

Wouldn't that release all variables in any case?

RBS
 
C

Charlie

ML0940 said:
There are also occasions to where I will set a string variable to "" when
done with it. That depends on the case and need ...

Really? A local string variable? Right before exiting the sub? Just
exactly when would there ever be a need for that? Don't worry, after 2 or 3
decades of including unnecessary lines of code you'll either get over it or
move into management.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top