gpt4 book ai didi

excel - 尝试将(仅)唯一值从列传递到 VBA 中的字典。验证未发生。我错过了什么?

转载 作者:行者123 更新时间:2023-12-04 22:17:41 25 4
gpt4 key购买 nike

基本上,我希望我的代码遍历一个范围内的值,并将唯一值添加到字典中。也就是说,如果之前没有添加过,则只添加第 n 个值。结果是一个字典,其中的键是范围内没有重复的所有值。这是我的代码:

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 i As Variant令人困惑:

  • i通常是一个计数器,例如一个 Long , 在 For...Next环形。
  • 如果您正在循环播放 RangeFor Each...Next循环,然后使用 Range为您的元素变量。

  • 所以 Dim cell As Range , 例如。
    然后,您需要明确说明 .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
    请注意,如果您只需要唯一值(键),则不必检查 Exists ,如 here 所示.同样的答案也证明了,将数据加载到 Variant 会更快首先数组,然后将数组读入字典。

    关于excel - 尝试将(仅)唯一值从列传递到 VBA 中的字典。验证未发生。我错过了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67425661/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com