2013-04-17 168 views
3

我試圖一次讀取一個單元格的列,並將單元格存儲爲鍵,並將其頻率存儲爲其值。然後我想把所有的鍵值對放到一個範圍內,比如P列和Q列。我想我已經完成了下面代碼的第一部分工作(儘管它不是100%)現在如何放置鍵值對到一個範圍?鍵值對,通過字典循環vba

Dim D As Dictionary 
Set D = New Dictionary 
Dim DR As Range 


Set DR = Range(Cells(2, 2), Cells(2, 2).End(xlDown)) 

    For Each Cell In DR.Cells 

     If Not D.Exists(Cell.Value) Then 
     D.Add Cell, 1 
     Else 
     D.Exists (Cell.Value) 
     D.Item(Cell.Value) = D.Item(Cell.Value) + 1 
     End If 

    Next Cell 

我大概有突破每每個鍵的字典循環的想法,但我不能做

Dim k as key 

任何的幫助深表感謝

回答

5

試試下面的代碼:

Sub test() 

    Dim D As Dictionary 
    Set D = New Dictionary 
    Dim DR As Range 


    Dim lastRow As Long 
    lastRow = Range("A65000").End(xlUp).Row 


    Set DR = Range("A2:A" & lastRow) 

    For Each Cell In DR 

     If D.Exists(CStr(Cell.Value)) = False Then 
       D.Add CStr(Cell.Value), 1 
     Else 
      D.Exists (Cell.Value) 
      D.Item(Cell.Value) = D.Item(Cell.Value) + 1 
     End If 

    Next 

    i = 2 
    For Each Key In D 
     Range("P" & i).Value = Key 
     Range("Q" & i).Value = D(Key) 
     i = i + 1 
    Next 


End Sub