【问题标题】:Excel VBA dictionary- How to get get Item values of Duplicate Key in cells?Excel VBA字典-如何获取单元格中重复键的项目值?
【发布时间】:2020-11-21 14:21:41
【问题描述】:

我正在尝试找到如何使用 Dictionary 删除重复值并连接单元格中的项目值的方法。

下面的代码正在做我想象的事情,但我可以在即时窗口中看到它(Debug.Print dict(People)。

字典 Keys(People) 的重复值的项目 (ID) 用逗号连接,但我不知道如何将这些项目提取到单元格。

所以 VBA 的想法是查找重复值并连接 ID 值并删除重复项。

谢谢!

Option Explicit

Sub DictionaryTest()
    
    Dim dict As Scripting.Dictionary
    Dim rowCount As Long
    Dim People As String
    Dim ID As Integer
    Dim item As Variant
    
    Set dict = New Scripting.Dictionary
    
    rowCount = Cells(Rows.Count, "E").End(xlUp).Row
    
    'Debug.Print rowCount
    
    Do While rowCount > 1
    
        People = Sheet2.Cells(rowCount, "E").Value
        ID = Sheet2.Cells(rowCount, "D").Value
        
        If dict.Exists(People) Then
            'Sheet2.Rows(rowCount).EntireRow.Delete
            
        Else
            dict.Add People, ID
        End If
        
        rowCount = rowCount - 1
        
    Loop
 
End Sub

【问题讨论】:

  • 您的代码中的实际列含义不匹配,并且未填写现有的字典键值...请测试我的答案代码。

标签: excel vba dictionary concatenation


【解决方案1】:

请试试这个改编的代码:

Sub DictionaryTest()
    Dim dict As New Scripting.Dictionary
    Dim rowCount As Long, i As Long
    Dim People As String
    Dim ID As Integer
    Dim sh As Worksheet
    
    Set sh = Sheet2
    rowCount = sh.cells(Rows.count, "D").End(xlUp).Row

    For i = 2 To rowCount
        People = sh.cells(i, "D").Value
        ID = sh.cells(i, "C").Value
        
        If dict.Exists(People) Then
           dict(People) = dict(People) & "," & ID
        Else
            dict.Add People, ID
        End If
    Next i
    sh.Range("F2").Resize(dict.count).Value = WorksheetFunction.Transpose(dict.Items)
    sh.Range("G2").Resize(dict.count).Value = WorksheetFunction.Transpose(dict.Keys)
End Sub

【讨论】:

  • 代码已经过测试,非常好。我需要学习/研究这些功能(调整大小、转置..),但它确实有效。在这段代码中,如果我希望值仅在单元格“C”和“D”中,而不是在“F”和“G”中,我只需要更改 sh.Range("F2") ..("G2 ") 到 "C" 和 "D" 槽循环。我理解正确吗?
  • @Mato Mišić 。很高兴我能帮助你!当必须删除数组时使用调整大小。范围必须适应数组维度。在这种特定情况下,dict.Count 返回字典元素编号。并且 dictionary.Keys 或 dictionary.Items 是一维数组。为了填充一列(就像我们的例子一样),它们必须被转置......而且,是的,可以按照您的建议定义要调整大小以删除字典元素的单元格。
  • @Mato Mišić:但是我们在这里,当有人花一些时间发布一段能够解决我们问题的代码时,请投票赞成代码,如果足够恶名或更重要,请勾选左侧代码复选框,以使其接受答案。这样,其他搜索类似问题的人就会知道该代码有效...... :)
  • 我可以用它做一些事情......很棒的代码!太感谢了! !
猜你喜欢
  • 1970-01-01
  • 2020-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多