EDIT: So it was really obvious, I needed the “Preserve” modifer for the Redim statement.
I’m trying to write a UDF in Excel VBA which takes a column of prices and selects the n highest/lowest buys/sells (marked in the adjacent column), and outputs ‘yes’ or nothing depending on whether a given cell meets those criteria.
As an example, for n = 2 the input could look something like this:
Price Type Result
150 buy yes
170 sell
146 sell yes
167 buy
125 buy
164 sell yes
So I’m counting through the price column, putting each price in either a ‘buy’ or ‘sell’ array, but for some reason when I look at the results only the last entries are showing up correctly, with the rest of the entries = 0.
Here’s the code I’ve got:
Function included(prices As Range, entry As Range)
n = 2
bc = 1 'counter for the buys
sc = 1 'counter for the sells
Ub = 1 'upper bound for buys
Us = 1 'upper bound for sells
Dim b() As Double 'dynamic array for buys
Dim s() As Double 'dynamic array for sells
'collect the buys and the sells into two arrays
For i = 1 To prices.Rows.Count
amt = prices(i).Value
If prices(i).Offset(0, 1) = "buy" Then 'add to buy list
ReDim b(1 To Ub) 'reapply length
b(bc) = amt 'add the entry
Ub = UBound(b) + 1 'add one to the length
bc = bc + 1 'increase the counter by 1
ElseIf prices(i).Offset(0, 1) = "sell" Then
'add to s
ReDim s(1 To Us)
s(sc) = amt
Us = UBound(s) + 1
sc = sc + 1
Else
MsgBox "nothing"
End If
Next
'check the resulting arrays (only the last value in b() and s() print out)
For i = 1 To UBound(b)
If b(i) <> 0 Then
MsgBox b(i)
End If
Next
For i = 1 To UBound(s)
If s(i) <> 0 Then
MsgBox s(i)
End If
Next
'still to do:
' sort the buy and sell arrays in ascending and descending order respectively
' truncate the arrays to length n
' check if entry is in one of the resulting arrays
End Function
I’m really new to VBA (and a mere Python novice), so maybe it’s something obvious? Thank you in advance for any help!
From the msdn library entry for
ReDim, thePreservemodifier needs to be included, so the code now readsReDim Preserve b(1 To Ub). Without the modifier the statement was emptying the array.