Home » excel » Passing a row range to Excel User Define Function and assign it to an array

Passing a row range to Excel User Define Function and assign it to an array

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am trying to

  1. pass two ranges – multiple column single row – to a user defined function in Excel 2007,
  2. then assigning it to an array for processing.

    Function MAE(actualData As Range, forecastData As Range) As Double

     Dim data
     Dim forecast
     Dim error As Double
     Dim average As Double
     Dim i As Long
    
     data = Application.Transpose(actualData)
     forecast = Application.Transpose(forecastData)
     average = 0
     error = 0
    
     For i = 1 To UBound(data)
    
       error = data(i) - forecast(i)
       If error < 0 Then
         error = error * -1
       End If
    
       average = error + average
    
     Next i
    
     MAE = average / UBound(data)
    
     End Function
    

I have posted a thread earlier in this forum, here is the link

In that thread I asked about passing a single column as Range to a user defined function. After your suggestions, I modified the code and it is working perfectly when I pass two single columns.

But when I pass two rows then it is not working. I am getting #Value error. Any suggestions about this?

How to&Answers:

THere’s a problem with the way you’re refering to your Variants by index.

If you review in the Locals window, you can see that the structure is a 2-dimensional array for each of data and forecast, but you are referring to them as 1-d arrays, which will cause the formula to fail.

Simply revise to:

error = data(i, 1) - forecast(i, 1)

And that should avoid the error.

Here is the Locals window, which shows the dimensions and lets you browse the arrays.

Screenshot of locals window