Using "Collection"

G

Greg

Wading into new territory here. When using a collection, how should it
be declared and set?

The below example seems to work, but I was wondering if it is more
appropriate or stable to both declare and set like:
Dim oBMCol as Collection
Set oBMCol = New Collection

Sub LessonCollection1()
Dim i As Integer
Dim ItemCount As Integer
ItemCount = ActiveDocument.Bookmarks.Count
Dim oBMCol As New Collection
For i = 1 To ItemCount
If InStr(ActiveDocument.Bookmarks(i).Name, "Test") <> 0 Then
oBMCol.Add "Bookmark " & i & " name: " & _
ActiveDocument.Bookmarks(i).Name
End If
Next i
'Now read back
For i = 1 To oBMCol.Count
MsgBox oBMCol(i)
Next i
End Sub

Maybe neither method is best so I am anxious to hear from an expert.
 
J

Jezebel

A lot of programmers (including me) never use 'Dim ... as new' for any kind
of object. Although it's not inherently evil -- and works perfectly well in
your example -- it's a style of programming that tends to spawn bugs. Apart
from anything else, you can never test whether the object is nothing.
Consider --

Dim x as new objecttype

do stuff with x
set x = nothing
if x is nothing then .... << will never be true, because the
reference re-instantiates the object.

So your first form of declaration is more robust coding.
 

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