0

I'm trying to write a simple VBA Function like this:

Public Function ReturnMMult(Arr1() As Variant, Arr2() As Variant) As Variant

    ReturnMMult = WorksheetFunction.MMult(Arr1,Arr2)

End Function

But it always gives me #VALUE! I've tried changing the Arr's to Ranges, but that doesn't work either. I basically want to be able to write functions that can take ranges like $A1:$A10 or something like that. Looked in a lot of places, and can't figure it out. What am I doing wrong?

4
  • Why do you want a function that replicates a worksheet function? Commented May 13, 2016 at 16:07
  • If I can solve this, I can solve my real problem. Just need to know how to do this in general. Commented May 13, 2016 at 16:10
  • It looks like MMult returns an array, try something like Public Function ReturnMMult(a As Excel.Range, b As Excel.Range) As Variant() Commented May 13, 2016 at 16:11
  • 1
    This may be an XY Problem - what's your ultimate goal? Commented May 13, 2016 at 16:12

3 Answers 3

3

something like

Public Function M(a As Excel.Range, b As Excel.Range) As Variant()
    Dim a1() As Variant
    Dim a2() As Variant
    a1 = a.value
    a2 = b.value
    M = Application.WorksheetFunction.MMult(a1, a2)
End Function
Sign up to request clarification or add additional context in comments.

1 Comment

You will need to add some checks that the columns in a is equal to the rows in b, and also, this error's, so you'll need to error trap to be safe. And also scott's post :)
1

You need to bring them in as ranges then shift them to arrays:

Public Function ReturnMMult(Arr1rng As Range, Arr2rng As Range) As Variant
Dim Arr1() As Variant: Arr1 = Arr1rng.Value
Dim Arr2() As Variant: Arr2 = Arr2rng.Value
ReturnMMult = WorksheetFunction.MMult(Arr1, Arr2)

End Function

enter image description here

Comments

0

This is an example of usage of MMult worksheet function. Please adopt it to your situation.

Sub test() 

    Dim xArray As Variant, yArray As Variant, zArray As Variant 
    Dim Fn As Object 
    Set Fn = Application.WorksheetFunction 

    xArray = Range("A1:B2").Value 
    yArray = Range("D1:E2").Value 
    zArray = Fn.MMult(xArray, yArray) 

    ActiveCell.Resize(2, 2).Value = zArray 

End Sub 

MMult returns the #VALUE! error when: Any cells are empty or contain text. The number of columns in array1 is different from the number of rows in array2. The size of the resulting array is equal to or greater than a total of 5,461 cells. Reference WorksheetFunction.MMult method

1 Comment

I'm trying to do this with the arrays as parameters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.