Beware of object scoping in Visual Basic

I’m doing some Visual Basic programming in Microsoft Word at the moment and spent some time on Friday trying to find out why all my objects (based on a Visual Basic class module) apparently had the same values. Apparently the following doesn’t work:

Dim col As New Collection
Dim i As Integer

For i=0 To 10
  Dim obj As New Person
  obj.Firstname = "Firstname" & i
  obj.Lastname = "Lastname" & i
  Call col.Add(obj)
Next

If you run the above code all the objects will hold Firstname10 and Lastname10 in their class variables. The solution is to do this instead:

Dim col As New Collection
Dim obj As Person
Dim i As Integer

For i=0 To 10
  Set obj = New Person
  obj.Firstname = "Firstname" & i
  obj.Lastname = "Lastname" & i
  Call col.Add(obj)
Next

The difference is that in the latter example the definition of the Person reference is done outside the loop while both the definition and the instantiation is done inside the loop in the first example. While both of the above cases are quite okay in LotusScript, and works as you would expect, you apparently have to define the reference outside the loop in Visual Basic for it to work. Why that would be the case is unclear to me…

Oh well… 🙂

2 thoughts on “Beware of object scoping in Visual Basic”

  1. Not a matter of being inside or outside the loop. Dim’s are always performed at script startup no matter where they are written. So its not really a scope matter either. :). First example only creates one person object upon startup.

    Like

  2. And there you have the explanation – I guess there’s to more to the difference between VB and LotusScript than simply a little bit of syntax… Thank you for the comment! 🙂

    Like

Comments are closed.