VBA Array Output for math function

aircrew

New Member
Joined
May 21, 2016
Messages
6
Hello, please help me with my problem. I need to create a function in VBA that will take an array as an argument and will return array containing squared values of the input array. That is, if A1=2 and B1 = 3, my function should return two cells containing numbers 4 and 9. Thanks for any advice
 
What about this:


Excel 2010
AB
124
239
3416
Sheet2
Cell Formulas
RangeFormula
B1:B3{=GetMathAnswer($A$1:$A$3)}
Press CTRL+SHIFT+ENTER to enter array formulas.

Code:
[COLOR=#0000ff]Function [/COLOR]GetMathAnswer(r [COLOR=#0000ff]As [/COLOR]Range)
[COLOR=#0000ff]  Dim[/COLOR] a [COLOR=#0000ff]As Variant[/COLOR]
[COLOR=#0000ff]  Dim[/COLOR] str [COLOR=#0000ff]As String[/COLOR]
  a = r
[COLOR=#0000ff]  For[/COLOR] i = 1 To [COLOR=#0000ff]UBound[/COLOR](a)
      a(i, 1) = a(i, 1) * a(i, 1)
[COLOR=#0000ff]  Next [/COLOR]i
  
  GetMathAnswer = a
[COLOR=#0000ff]End Function[/COLOR]

Don't really see how it's any different than A1*A1.....
 
Upvote 0

Excel Facts

Last used cell?
Press Ctrl+End to move to what Excel thinks is the last used cell.
Thank you very very much, thats exactly what I needed. As I said I need to adjust it for a more complex function, not just squared and this is very helpful. Thanks
 
Upvote 0
Thank you very very much, thats exactly what I needed. As I said I need to adjust it for a more complex function, not just squared and this is very helpful. Thanks
I think the point of mrmmickle1's final comment (and my comment in Message #4) is that no matter how complex the function, you should be able to create an Excel formula using native worksheet functions that can be copied into each output cell which will do its calculations more efficiently than an array-entered UDF that outputs the same values into those same cells.
 
Upvote 0

Forum statistics

Threads
1,223,099
Messages
6,170,107
Members
452,302
Latest member
TaMere

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top