vba字典删除重复
Posted
技术标签:
【中文标题】vba字典删除重复【英文标题】:vba dictionary remove duplicate 【发布时间】:2020-12-14 12:59:47 【问题描述】:我正在尝试学习字典的工作原理,我知道它们类似于集合,但我不太明白有些东西,现在这是我的测试工作:
我有一些这样的价值观
然后我将所有内容放入带有模块的字典中,因为我想将列中的值与另一个值进行比较
Sub dict()
Dim diz As New Dictionary
Dim ora As classe
Dim rg As Range
Set rg = Foglio4.Range("b2:b700")
For i = 2 To 700
Set ora = New classe
ora.old = rg.Cells(i, 1).Value
ora.turn = rg.Cells(i, 2).Value
diz.Add ora, i
Next i
If diz.Exists("4072") = True Then
MsgBox "esiste"
End If
End Sub
在 diz 中,我有所有值,例如,diz item (1) "4072","1602"
但我想删除重复项
就是不知道怎么弄
我尝试使用 Exists 函数,但它总是返回错误
目标是这样的
我在字典中搜索一个数字,然后我在另一列中返回了值
我希望你能帮助我更好地理解字典
提前谢谢你
【问题讨论】:
字典中的键总是唯一的。项目可以多次使用不同的键。查看此页面以了解有关字典的更多信息:excelmacromastery.com/vba-dictionary espacialy 在这部分中查看,以了解如何添加新的键/项对或更新现有键的项excelmacromastery.com/vba-dictionary/… 字典也有 Exists() 方法,集合中不存在。 还要记住关系是倒置的。您不会从字典中删除重复项,因为它们从未真正添加过。工作流程应该是(1)识别唯一的键值,(2)检查该值是否已经被添加(使用Exists
),(3)如果没有,然后添加到dict,否则做你需要的任何操作做。
【参考方案1】:
字典示例
了解Dictionary
对象here、here 和here
守则
Option Explicit
Sub dict()
Dim diz As New Dictionary
Dim ora As classe
Dim rg As Range
Dim i As Long
Set rg = Foglio4.Range("B2:C700")
For i = 2 To 700
Set ora = New classe
ora.old = rg.Cells(i, 1).Value
ora.turn = rg.Cells(i, 2).Value
If Not diz.Exists(ora.old) Then
diz.Add ora.old, ora.New
End If
Next i
If diz.Exists("4072") = True Then
MsgBox "esiste"
End If
End Sub
' Strings
Sub dict2()
Dim diz As New Dictionary
Dim Data As Variant
Dim rg As Range
Dim i As Long
Set rg = Foglio4.Range("B2:C700")
Data = rg.Value
For i = 1 To UBound(Data)
If Not diz.Exists(CStr(Data(i, 1))) Then
diz.Add CStr(Data(i, 1)), CStr(Data(i, 2))
End If
Next i
If diz.Exists("4072") Then
MsgBox "The Key '4072' contains the value '" & diz("4072") & "'."
End If
End Sub
'Numbers
Sub dict3()
Dim diz As New Dictionary
Dim Data As Variant
Dim rg As Range
Dim i As Long
Set rg = Foglio4.Range("B2:C700")
Data = rg.Value
For i = 1 To UBound(Data)
If Not diz.Exists(Data(i, 1)) Then
diz.Add Data(i, 1), Data(i, 2)
End If
Next i
If diz.Exists(4072) Then
MsgBox "The Key '4072' contains the value '" & diz(4072) & "'."
Else
MsgBox "The Key '4072' doesn't exist."
End If
End Sub
' No reference needed. No dictionary variable, no range variable.
Sub dict4()
With CreateObject("Scripting.Dictionary")
Dim Data As Variant: Data = Foglio4.Range("B2:C700").Value
Dim i As Long
For i = 1 To UBound(Data)
If Not .Exists(Data(i, 1)) Then
.Add Data(i, 1), Data(i, 2)
End If
Next i
If .Exists(4072) Then
MsgBox "The Key '4072' contains the value '" & .Item(4072) & "'."
Else
MsgBox "The Key '4072' doesn't exist."
End If
'Debug.Print "Keys" & vbLf & Join(.Keys, vbLf)
'Debug.Print "Values (Items)" & vbLf & Join(.Items, vbLf)
End With
End Sub
【讨论】:
感谢 vbasic2008,现在我看到了您的潜艇,我开始了解它是如何工作的,感谢您提供的链接以上是关于vba字典删除重复的主要内容,如果未能解决你的问题,请参考以下文章