【问题标题】:VBA Dictionary of dictionaries?VBA词典?
【发布时间】:2015-11-19 15:11:55
【问题描述】:

我正在使用字典对象从工作表中列标题下的每一列创建唯一的集合。列标题在第 1 行。

问题是我的字典包含以前列中的唯一项目。例如,如果调用第 4 列的字典,它包含第 1、2、3 列中的所有唯一项目和标题。我只需要该列中的唯一项目。知道如何更正此代码吗?

Sub cre_Dict()
Dim fulArr As Variant

Set d = CreateObject("scripting.dictionary")

With Sheets("Database")
        fulArr = .Range("A1:IO27") 'assign whole table to array
        For j = 1 To UBound(fulArr, 2) 'looping from 1st column to last column
            For i = 2 To UBound(fulArr, 1) 'looping from row2 to last row
                If Len(fulArr(i, j)) > 0 Then 'if not blank cell
                    d00 = d.Item(fulArr(i, j)) 'add to dictionary
                End If
            Next i
            d(fulArr(1, j)) = d.keys 'create dictionary under column heading
        Next j
End With

End Sub

谢谢

【问题讨论】:

  • 您应该添加一些 cmets,既为我们也为您自己;很难准确地说出您在这里要做什么。
  • 与之前的一些问题几乎相同的代码,没有明确的解释,你仍然使用空字典......
  • 我的字典怎么是空的?。 d 是全局对象。
  • @Shan How is my dictionary empty?. d is global object. - 我们应该怎么知道除非你把它放在你的问题中?

标签: excel vba dictionary


【解决方案1】:

考虑下面的例子,基于你的代码,我做了一些小的改动:

Dim d As Object

Sub cre_Dict()
    Dim fulArr As Variant
    Dim q As Object
    Dim j As Long
    Dim i As Long

    Set d = CreateObject("Scripting.Dictionary")
    fulArr = Sheets("Database").Range("A1:IO27") 'assign whole table to array
    For j = 1 To UBound(fulArr, 2) 'looping from 1st column to last column
        Set q = CreateObject("Scripting.Dictionary")
        For i = 2 To UBound(fulArr, 1) 'looping from row2 to last row
            If Len(fulArr(i, j)) > 0 Then 'if not blank cell
                q(fulArr(i, j)) = Empty 'add to dictionary
            End If
        Next i
        d(fulArr(1, j)) = q.Keys 'create dictionary under column heading
    Next j

End Sub

【讨论】:

    【解决方案2】:

    如果我没看错,那么您在不同的列中有重复项。所以基本上你在字典中的键在你迭代列时不是唯一的。如果是这种情况,当您将键添加到字典时,请创建一个复合键。例如:

    Dim sKey 作为字符串 sKey = "A~" & "ABCD"

    这将使 A 列的键唯一。 处理集合时,可以去掉每一列的“A~”部分。

    【讨论】:

      猜你喜欢
      • 2018-03-07
      • 2010-09-22
      • 2019-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多