键值对,循环通过字典vba

时间:2013-04-17 18:58:01

标签: vba excel-vba excel

我试图一次读取一列单元格,并将单元格作为键存储,并将其频率作为其值。然后我想将所有键值对放在一个范围内,比如列P和Q.我想我已经完成了下面代码完成工作的第一部分(虽然不是100%)现在如何放置键值对到一个范围?

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

非常感谢任何帮助

1 个答案:

答案 0 :(得分: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