Forum Discussion
Deleted
Jun 17, 2020VBA code for inputs
I've written a function in Matlab that calculates the average growth rate for i.g. a companys profit. Profit is sometimes negative, so I've solved this "issue" with a couple of for-loops and if-stat...
Andrew_Duncan54
Jan 23, 2021Brass Contributor
Not quite sure what you are attempting, as I'm not familiar with Matlab.
But the guts of your function should look much the same as what you have written:
Function someFunction(y As Variant) As Variant
Dim growth() As Variant
Dim i As Long
ReDim growth(LBound(y) To UBound(y))
For i = 1 To UBound(y) - 1
If y(i) < 0 And y(i + 1) < 0 Then
growth(i) = y(i) / y(i + 1)
ElseIf y(i) > 0 And y(i + 1) > 0 Then
growth(i) = y(i + 1) / y(i)
ElseIf y(i) < 0 And y(i + 1) > 0 Then
growth(i) = (y(i + 1) - (y(i)) / (-y(i)))
Else
growth(i) = 0
End
End
someFunction = growth
End FunctionIf you paste your raw data into an excel spreadsheet as a single row or column. In another cell reference, the function "someFunction" (or whatever you have called it), for the function input, have the range of cells referring to your input data (i.e. A1:A100, etc), the above code will return an array of growth values.
With the lower bit of code, not quite sure what that is doing. Excel has good inbuilt functions for generating AVERAGE. Either use excels Functions to process the output or put the cove into the VBA Function.
Hope this helps.