Microsoft KB Archive/129871

= PRB: "Object not a Collection" Trying to Read Array Element =

Article ID: 129871

Article Last Modified on 12/9/2003

-

APPLIES TO


 * Microsoft Visual Basic 4.0 Standard Edition
 * Microsoft Visual Basic 4.0 Professional Edition
 * Microsoft Visual Basic 4.0 Professional Edition
 * Microsoft Visual Basic 4.0 16-bit Enterprise Edition
 * Microsoft Visual Basic 4.0 32-Bit Enterprise Edition

-



This article was previously published under Q129871



SYMPTOMS
If a public member of a class of type variant is assigned an array, you get the following error message when trying to read an element of the array by directly indexing the variant member:

Object not a Collection.

This happens only if the instance of the class object is late bound; that is, the instance is dimensioned "As Object."



RESOLUTION
 Dimension the object instance as being of the exact type of the class, so that it is Early Bound. -or-

  Index the variant member with another level of parenthesis. For example, in the "Steps to Reproduce Behavior" section of this article, use: Debug.Print x.arr(0)

Instead of:

Debug.Print x.arr(0) This explicitly specifies that the variant holds an array. 



STATUS
This behavior is by design.



Steps to Reproduce Behavior
 Start a new project in Visual Basic. Form1 is created by default. Choose Module from the Insert menu to add a new standard module (Module1)  Add the following code to Module1: Sub main Dim a(2) As Integer a(0) = 5

Dim x As Object Set x = New Class1

x.arr = a        Debug.Print x.arr(0) End Sub </li> Choose Class Module from the Insert menu to add a new class module (Class1).</li>  Add the following code to Class1: Public arr As Variant </li> Press the F5 key to run the program. You will get the error message on the Debug.Print line.</li></ol>

Example Workaround
To work around the behavior, declare the object with a specific object type instead of Object. In Step 3 above, replace: Dim x As Object

with:

Dim x As New Class1 Then change the Set statement into a comment. After making these changes, run the program again. You should see a value of 5 in the Debug Window.

Keywords: kbprogramming kbprb KB129871

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.