Excel 在VBA中尝试将(仅)唯一值从列传递到字典。验证没有引起注意。我错过了什么?
基本上,我希望我的代码遍历某个范围内的值,并只向字典中添加唯一的值。也就是说,如果之前未添加第n个值,则仅添加该值。结果是一个字典,其中键是该范围内的所有值,没有重复项。这是我的密码:Excel 在VBA中尝试将(仅)唯一值从列传递到字典。验证没有引起注意。我错过了什么?,excel,vba,dictionary,Excel,Vba,Dictionary,基本上,我希望我的代码遍历某个范围内的值,并只向字典中添加唯一的值。也就是说,如果之前未添加第n个值,则仅添加该值。结果是一个字典,其中键是该范围内的所有值,没有重复项。这是我的密码: Sub CreatePatientList() Dim outputsh As Worksheet Set outputsh = Workbooks(1).Sheets(1) Dim recDict As New Scripting.Dictionary Dim i As Va
Sub CreatePatientList()
Dim outputsh As Worksheet
Set outputsh = Workbooks(1).Sheets(1)
Dim recDict As New Scripting.Dictionary
Dim i As Variant, rowCount As Long
rowCount = outputsh.Cells(Rows.Count, 1).End(xlUp).Row
For Each i In Range("O2:O" & rowCount)
If recDict.Exists(i) Then
MsgBox ("Exists")
Else
recDict.Add i, i
End If
Next
Set recDict = Nothing
End Sub
现在,该范围内100%的值都被添加到字典中
Dim cell As Range, rowCount As Long
...
For Each cell In Range("O2:O" & rowCount)
If recDict.Exists(cell.Value) Then
MsgBox "Exists"
Else
recDict.Add Key:=cell.Value, Value:=cell.Value
End If
Next
有什么帮助吗?提前谢谢
Dim i作为变体
令人倍感困惑:
通常是一个计数器,例如i
,在Long
循环中For…Next
- 如果您在一个
范围内循环,每个循环都有一个
循环,那么对元素变量使用一个,下一个
范围
将单元格变暗为范围
然后,需要明确键的单元格的.Value
。目前,范围是键,而不是它的值,由于每个范围都是唯一的,因此它们都被添加到字典中
Dim cell As Range, rowCount As Long
...
For Each cell In Range("O2:O" & rowCount)
If recDict.Exists(cell.Value) Then
MsgBox "Exists"
Else
recDict.Add Key:=cell.Value, Value:=cell.Value
End If
Next
请注意,如果只需要唯一的值(键),则不必检查是否存在
,如图所示。同样在同一个答案中也演示了,首先将数据加载到变量
数组中,然后将该数组读入字典会更快
Dim cell As Range, rowCount As Long
...
For Each cell In Range("O2:O" & rowCount)
If recDict.Exists(cell.Value) Then
MsgBox "Exists"
Else
recDict.Add Key:=cell.Value, Value:=cell.Value
End If
Next