Simple question about setting objects = Nothing

  • Thread starter Thread starter phil
  • Start date Start date
P

phil

I frequently Exit out of subs and functions after setting
db = CurrentDb or rs = db.OpenRecordset(somestring).

Should I be setting these objects to = Nothing before I
do my Exit Sub or Exit Function?
 
Yes! Any objects you create such as db or anything you open such as rs should be
set to Nothing at the end of your procedure.
 
Yup... not only should you set them to nothing, you should close them first.
IE:

myRS.Close
Set myRS = Nothing
myDB.Close
Set myDB = Nothing

Although, variables declared at the procedure level, are only available
within that procedure, and thus, when any sub or function is exited, those
variables are destroyed, they should be "gracefully" closed. Not closing and
setting them to nothing, has been compared, with stopping a bus, by driving
it into a brick wall, instead of using the brakes.

It is always advisable to close and set the variables to nothing, to help
prevent any corruption to the connected data source from abrupt
terminations.
 
Ruskin Hardie said:
Yup... not only should you set them to nothing, you should close them
first. IE:

myRS.Close
Set myRS = Nothing
myDB.Close
Set myDB = Nothing

Although, variables declared at the procedure level, are only
available within that procedure, and thus, when any sub or function
is exited, those variables are destroyed, they should be "gracefully"
closed. Not closing and setting them to nothing, has been compared,
with stopping a bus, by driving it into a brick wall, instead of
using the brakes.

It is always advisable to close and set the variables to nothing, to
help prevent any corruption to the connected data source from abrupt
terminations.

I second this advice, with a qualification about closing objects. If
you opened the object, you should close it. If you didn't open it,
though, you shouldn't close it. So if you used "Set rs =
db.OpenRecordset", then you should say "rs.Close" before "Set rs =
Nothing". But if you used "Set ws = Workspaces(0)" to get a reference
to the current workspace, you should *not* say "ws.Close", though you
should set ws = Nothing when you're done with it.

Technically you aren't *supposed* to have to set local object variables
to Nothing, as they *should* be destroyed by VB when the procedure
exits. However, there have been bugs in this process in the past, so I
make it a policy to do it anyway.
 
Back
Top