2016-02-25 78 views
1

我在總結VBA中一個數組的特定條目時遇到了問題。我給你我的矩陣看起來像一個例子(我們稱之爲矩陣「startMatrix」)在VBA條件下總結一個數組的特定條目

Date  ticker  value 
2005.01 200   1000 
2005.01 300   2222 
2005.01 400   2000 
2005.02 200   1100 
2005.02 300   3000 
2005.02 400   5555 

在VBA中的矩陣然後閱讀這樣的:

startMatrix(1,1) = 2005.01 
startMatrix(1,2) = 200 
startMatrix(1,3) = 1000 
startMatrix(2,1) = 2005.01 
startMatrix(2,2) = 300 
.... 
startMatrix(6,3) = 5555 

所以我想總結每個日期的值,如果股票是200或300並保存這個新數組(我們稱之爲finalMatrix)。該finalMatrix應該是這樣的,那麼:

Date  Value 
2005.01 3222 
2005.02 4100 

的finalMatrix應該是這樣的VBA底:

finalMatrix(1,1) = 2005.01 
finalMatrix(1,2) = 3222 
finalMatrix(2,1) = 2005.01 
finalMatrix(2,2) = 4100 

我不是很習慣這些類型的業務,所以我會真的,真的感謝你的幫助。 謝謝你,祝你有個美好的一天 Elio

回答

2

你會最好的使用字典,而不是陣列的輸出。

啓用Microsoft腳本運行時參考

當使用字典,你可以輸入日期作爲重點。然後,您可以對startMatrix數組的每次迭代進行評估,確定日期是否已經存在爲鍵。如果沒有,那麼您創建一個新的密鑰並添加該值。如果它確實存在,則將分配給該鍵的值添加到數組中。

Option Explicit 

Public Sub sum_values() 

    Dim wb As Workbook, ws As Worksheet 
    Dim dict As Scripting.Dictionary 
    Dim startMatrix() As Variant 
    Dim i As Long 

    Set wb = ThisWorkbook 
    Set ws = wb.Sheets(1) 

    startMatrix = ws.Range("A2:C7") 

    Set dict = New Scripting.Dictionary 

    For i = LBound(startMatrix, 1) To UBound(startMatrix, 1) 

     If Not dict.Exists(startMatrix(i, 1)) Then 

      dict(startMatrix(i, 1)) = startMatrix(i, 3) 

     Else 

      dict(startMatrix(i, 1)) = dict(startMatrix(i, 1)) + startMatrix(i, 3) 

     End If 

    Next i 

End Sub 

喜歡的東西上面會爲你工作。 Here是詞典的一些閱讀材料。

你甚至可以排除If語句,只是有For...Next語句中這1行:

dict(startMatrix(i, 1)) = dict(startMatrix(i, 1)) + startMatrix(i, 3) 
+0

哇,你thak非常爲你快速而深刻的響應。我會仔細看一下字典,看起來很有用。 代碼工作得非常好,非常感謝你,祝你有美好的一天! –