4

我正在尝试一次读取一个单元格并将其存储为单元格并将其频率作为其值。然后我想将所有键值对放入一个范围内,比如列 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

任何帮助深表感谢

4

1 回答 1

6

试试下面的代码:

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
于 2013-04-17T19:33:20.477 回答