Visual Basic 6 Array as Argument

Tag: arrays , vb6 , parameter-passing Author: caofujunbeijing Date: 2011-05-02

This might sound like a stupid question, but I am about to pull hear out.

I have a Sub whereby I want to parse an array and assign it to a Class Module "Object".

How do I go about doing this.

What I do have that isn't working is:

Private matrix(9,9) As Integer
'The Setter Sub
Public Sub SetMatrixArray(arrValToSet() as Integer)
    matrix = arrValToSet
End Sub


'In the caller module / class module I have the following code to parse the array.

Dim theArray(9,9) As Integer
Dim customObj as CustomObject
customObj.SetMatrixArray(theArray)

I get the following error message:

Type mismatch: array or user-defined type expected.

Dabblernl's answer should work. And if you have more issues, this seems to be quite a good resource for arrays (it's about VBA, but that's close enough to be helpful).
@ho1 I don't disagree, but his syntax for calling SetMatrixArray is incorrect. I'm looking at this. Am I wrong?
@Jay: No, I think you're completely correct. I'm too used to VB.Net so I didn't even notice those extra parentheses until now. I think a combination of yours and Dabblernl's answers are needed.

Best Answer

This works:

 'In the caller module / class module I have the following code to parse the array.'
    Dim theArray(9,9) As Integer 
    Dim customObj as CustomObject 
    customObj.SetMatrixArray theArray

'The Class'

Private matrix() As Integer 
       'The Setter Sub '
       Public Sub SetMatrixArray(arrValToSet() as Integer)
       matrix = arrValToSet
    End Sub 

So remove the dimensioning of the matrix array in your class. You can always implement errorchecking if the dimensions must be exactly 9.

EDIT: I removed the parens around the procedure calling without thinking while testing, it may influence the answer.

comments:

Yes, this is called "declaring a dynamic array."
VB doesn't allow you to re-assign an array where you already gave it a size. The above statement does not work.
Let me rephrase. It does work if the theArray() is not assigned a value of theArray(9,9). I modified the answer. Good job. Learned something new today!

Other Answer1

I think you need to pass the array as a variant for multidimensional arrays

Public Sub SetMatrixArray(arrValToSet as Variant)
    matrix = arrValToSet
End Sub

Check out this article.

Other Answer2

When you call customObj.SetMatrixArray() try either:

Dropping the parens around the procedure parameter:

customObj.SetMatrixArray theArray

-- or --

Prefacing your call with Call:

Call customObj.SetMatrixArray(theArray)

comments:

+1 You can run into odd cases in VB6 where adding additional parentheses turns your argument into an expression