Share via

Clearing object variables from RAM upon conclusion of procedure - VBA

Charles Kenyon 167.7K Reputation points Volunteer Moderator
2019-03-19T13:16:06+00:00

I recall being taught that good programming clears object variables from RAM by setting them to nothing at the conclusion of a procedure.

Is my recollection correct?

Is this still a good programming procedure with VBA?

Microsoft 365 and Office | Word | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

Answer accepted by question author

Jay Freedman 207.7K Reputation points Volunteer Moderator
2019-03-19T16:34:39+00:00

Yes, it's a good practice to follow. It often doesn't make any difference, especially if the objects are small, but always doing it forms a good habit.

VBA *should* clear all local variables (those whose Dim statements appear inside a procedure) from memory as the procedure ends, but I'm not sure that always happens for object variables. The difference is that scalar (non-object) variables are stored at addresses within the procedure's stack, but object variables are stored on the "heap" and then referenced by a pointer. Clearing the stack is easy, but cleaning up the heap is harder.

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Charles Kenyon 167.7K Reputation points Volunteer Moderator
    2019-03-19T18:06:24+00:00

    Thank you Jay. I will continue to do it, it can't hurt.

    Was this answer helpful?

    0 comments No comments
  2. Charles Kenyon 167.7K Reputation points Volunteer Moderator
    2019-03-19T16:30:22+00:00

    Although others are welcome to chime in, I think I found the answer.

    In general subroutines, unless the object is holding a LOT of information, don't bother. It will be emptied when it loses scope.

    Was this answer helpful?

    0 comments No comments