PDA

View Full Version : [SOLVED:] Basic question from a newbie



stevetalaga
03-01-2014, 09:22 PM
As a newbie to Word VBA but with a little programming experience in the past I have a basic question about variables.

If you declare variables within a Module or Sub Procedure do you need to "release" them at the end of the module / sub procedure in order to free up the memory that they are using or do they get killed off automatically if they are not declared as static? I tried searching for "Release" in the Help screen but it's not there.

Thanks

fumei
03-02-2014, 04:03 AM
The VBA garbage collector will automatically destroy the variable when its Scope terminates. So no, you do not need to release them explicitly. That said, there is arguably an exception. Application objects (e,g, Excel or Word, but especially Word) can hang around longer than intended. And, as Word is multi-instance application it is quite possible to have a number of Word application running at the same time. This can suck up huge amounts of memory. There are still scenarios where VBA does NOT destroy an instance,

So, IMO:

Do not sweat all your strings, numbers, or Application child objects like table objects or bookmark objects or header objects etc etc. The garbage collector should do its job.

To be on the safe side though, explicitly destroy your application objects (and maybe your Document objects) when you are finished with them. I must admit I also destroy Range objects, especially when they are in loops with a lot of resizing.

This is a strongly debatable subject, so the above is just my opinion.

stevetalaga
03-02-2014, 06:49 PM
Thanks Fumei