I have an array (AlphaVector) with the following values:
-0.2
-0.7
0
0.4
0.3
0.1
I want to pick the positive values from the above array and place it in another array named Alpha so that I can pick the minimum positive value from Alpha. My goal is to get the value 0.1 from the above array.
Here’s the code I have so far. Alpha gets populated ok as the Msgbox indicates the correct values, but the return value I am getting is 0 instead of 0.1.
Function FindMin(AlphaVector)
Dim iCount As Long
Dim N As Integer, i As Integer
N = AlphaVector.Cells.Count
Dim Alpha() As Double
ReDim Alpha(N) As Double
For i = 1 To N
If AlphaVector(i) > 0 Then
Alpha(i) = AlphaVector(i)
Else
Alpha(i) = 100000000000#
End If
MsgBox ("Alpha(i)= " & Alpha(i))
MsgBox ("AlphaVector(i)= " & AlphaVector(i))
Next i
FindMin = WorksheetFunction.Min(Alpha)
End Function
Can you please tell me how to fix it? Also, if there is a more efficient way to write it, perhaps without introducing Alpha, please let me know. Thanks.
You are using the wrong index for array
Alpha. It is zero-based, and since you populate it by usingi, starting from 1, you leaveAlpha(0)to be the default, which is 0.WorksheetFunction.Min(Alpha)returns the smallest value, which you now know always will be 0. 🙂You need to redesign your function to handle this. Example will follow shortly.
EDIT – code sample – updated to work as a UDF
I finished this sample before I saw your comments, so in my code
AlphaVectoris an array. Anyway, it is always better to explicitly declare any variables and avoid theVarianttype if you can, which is used if you don’t declare variables. This is why I’m usingOption Explicit. You should too. 🙂There are probably a lot of ways to do what you want, but this is one: