Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

VBA function works within a sub procedure but not on the excel worksheet: "value" error. Probably an issue with one argument being an array

I want to write a function which given 2 arguments (2 dimensional array with n rows and p columnns and a number i) it will return the i^th column of the matrix. I have written this code using an array and when I use it within a sub procedure it works but when I try to use the function on the excel worksheet I get a #value error.
Here is the function code I have written:(option base 1 because of the matrices)


Function extractcolumn(mat() As Variant, colnum As Integer) as variant
numrow = UBound(mat, 1)
ReDim Results(numrow, 1)

For i = 1 To numrow
    Results(i, 1) = mat(i, colnum)
Next i

extractcolumn = Results
End Function

which works in this sub procedure:


Sub testfunction()
n = Range(Range("A1"), Range("A1").End(xlDown)).Rows.Count
p = Range(Range("A1"), Range("A1").End(xlToRight)).Columns.Count
ReDim matrix(n, p)

For j = 1 To p
    For i = 1 To n
        matrix(i, j) = Cells(i, j).Value
    Next i
Next j

ret = extractcolumn(matrix, 2)
End sub

To solve my problem I have tried using a range as input which works both on the excel worksheet and the sub procedure but it is just not as efficient and requires more line.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Function extractColumn(Matrix As Range, colIndex As Integer) As Variant 
    n = Matrix.Rows.Count 'the total number of rows in the range 
    p = Matrix.Columns.Count 'the total number of columns in the range 
 ReDim result(n, 1) 

    For i = 1 To n 

        result(i, 1) = Matrix.Cells(i, colIndex).Value 

    Next i 

    extractColumn = result 

End Function 

I would love to hear your inputs to solve my problem !

>Solution :

If you declare your argument as Variant or Variant array:

mat() As Variant

you should call this function with an array argument, not simply a range.
If you want to access a range values e.g. A5:C7 you should write:
+A5:C7 (universal) or
--A5:C7 (numbers) or
A5:C7&"" (text strings).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading