2015-09-29 52 views
0

我有一個從服務調用返回的對象列表。數據範圍轉換

Object has below attributes: 
DateVal1 
DateVal2 
Value 

我怎樣分配對象爲2D矩陣範圍的範圍內:如果沒有與行,列組合打印值別的打印NA對象 日期1作爲列,日期2作爲標題行

數據可能很大(最大30x30),所以試圖避免每次都在列表中查找。

Date  1/31/2015 2/28/2015 3/31/2015 
1/1/2015 1   NA   NA 
1/2/2015 NA  2   NA 
1/3/2015 NA  NA   3 

如果這個略有不同,該怎麼辦?

Object has below attributes: 
    DateVal1 
    DateVal2 
    Value1 
    Value2 

和所需的O/P是這樣的:

Date1  Date2    110  20   30 
1/1/2015 1/10/2015   1   NA   NA 
1/2/2015 1/20/2015   NA   2   NA 
1/3/2015 1/31/2015   NA   NA   3 
+0

不要使用'Date'作爲變量,因爲它是預先定義的功能,返回當前日期。 – omegastripes

+0

我已經更新了ref代碼。 – Cannon

+0

您可以使用幾個腳本字典對象將日期映射到列/行號。列/行標題是否預先定義好了,還是從列表(數組?)對象中填充它們? –

回答

2

未經檢驗的,但這樣的事情:

Sub Test() 

    Dim points, i As Long, r As Long, c As Long 
    Dim dictRows, dictCols, grid(0, 0) 
    'dictionary to map "key" values to row numbers 
    Set dictRows = CreateObject("scripting.dictionary") 
    'dictionary to map "key" values to column numbers 
    Set dictCols = CreateObject("scripting.dictionary") 

    points = getPoints() 
    r = 0 
    c = 0 

    '[sort points by date1 here] 
    'map date1 to "row" 
    For i = LBound(points) To UBound(points) 
     If Not dictRows.exists(points(i).date1) Then 
      r = r + 1 
      dictRows.Add points(i).date1, r 
     End If 
    Next i 
    '[sort points by date2 here] 
    'map date2 to "column" 
    For i = LBound(points) To UBound(points) 
     If Not dictCols.exists(points(i).date2) Then 
      c = c + 1 
      dictCols.Add points(i).date2, c 
     End If 
    Next i 

    ReDim grid(1 To r, 1 To c) 

    For i = LBound(points) To UBound(points) 
     grid(dictRows(points(i).date1), dictCols(points(i).date2)) = points(i).Value 
    Next i 

    'populate on worksheet 
    With ActiveSheet 
     .Range("A2").Resize(r, 1).Value = Application.Transpose(dictRows.keys) 
     .Range("B2").Resize(r, c).Value = grid 
     .Range("B1").Resize(1, c).Value = dictCols.keys 
    End With 

End Sub 
+0

這是完美的。我會發布它的測試版本。非常感謝。 – Cannon

+0

如果我的物體結構略有不同,該怎麼辦?日期1,日期2,VAL1,VAL2?我編輯了問題。或者需要單獨的問題? – Cannon

+0

嘗試調整我寫的示例,並在遇到問題時使用代碼發佈新問題。 –