0
編輯:所以它非常明顯,我需要Redim語句的「Preserve」修飾符。VBA中的數組填充問題
我試着寫在Excel VBA一個UDF這需要價格的一列,並選擇ñ最高/最低購買/賣出(標註在相鄰列),並輸出「是」或沒有根據一個給定的小區是否符合這些標準。
舉個例子,對於ñ = 2的輸入可以是這個樣子:
價格類型結果
150買的是
170賣
146賣是
167買
125購買
164賣是的
所以我通過價格列計數,把每個公關在'buy'或'sell'數組中,但由於某種原因,當我查看結果時,只有最後一個條目正確顯示,其餘條目= 0.
下面是代碼I' ve得到了:
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
我真的是新來的VBA(和一個純粹的Python新手),所以也許這是明顯的東西?預先感謝您的任何幫助!
當您使用ReDim時,數組將被清空,這就是爲什麼您只能看到最後一個條目。要保留這些值,請使用'保留',如'Redim Preserve b(1 To Ub)' – CaBieberach 2012-03-09 07:33:52
請注意,您可以回答自己的問題(它甚至是[強烈推薦](http://meta.stackexchange.com/questions/17463/can-i-answer-my-own-questions-even-that-where-i-know-the-answer-before-asking))並接受它。這樣,您可以與社區分享您的知識,並*關閉*問題。 – JMax 2012-03-09 08:49:34