When do I need to place objects in VBA

Looking at this code (most of which has been removed to simplify this question), I began to wonder if I need to recycle the collection or class that I used.

Option Explicit    
Private terminals As Collection

Sub BuildTerminalSummary()
  Dim terminal As clsTerminal
  Call LoadTerminals
  For Each terminal in terminals
  ...Do work here
  Next terminal

  Set terminals = Nothing

End Sub

Private Sub LoadTerminals()
  Do
    Set terminal = New clsTerminal

    ...Do work here

    'Add terminal to terminals collection
    terminals.Add terminal, key

  Loop Until endCondition
End Sub

When you work with VBA, when should I dispose of the object (if ever)?

+3
source share
1 answer

It seems to me that you have the opportunity for a collection of terminals in the wrong place. Ask LoadTerminals to return the collection of created terminals: -

Option Explicit    

Sub BuildTerminalSummary()

  Dim terminals As Collection
  Dim terminal As clsTerminal

  Set terminals = LoadTerminals

  For Each terminal in terminals
  ...Do work here
  Next terminal

End Sub

Private Function LoadTerminals() As Collection
  Dim terminals As Collection : Set terminals = New Collection
  Do
    Set terminal = New clsTerminal

    '' # ...Do work here

    terminals.Add terminal, key

  Loop Until endCondition

  Set LoadTerminals = terminals

End Function

As long as you have variables, there is no need to especially β€œdelete” them (which, I think, you mean assigning a Nothingvariable containing a link to them.

+3
source

Source: https://habr.com/ru/post/1723147/


All Articles