Excel VBA : This key is already associated with an element of this collection

标签 excel vba

目标:

我有一些变量已声明为变体,我想将它们添加到字典中,以便循环遍历它们并动态地向它们添加值。我希望它们使用 Null 的值进行初始化,因为稍后我会将它们传递到 sql 语句中,如果没有可用的值,它们需要为 Null。这些值将来自 Excel 中的一系列单元格。

错误:

Run-time error '457':

This key is already associated with an element of this collection



代码:
Dim Entity As Variant
Dim Project As Variant
Dim Status As Variant
Dim Draft As Variant
...

Set d = CreateObject("Scripting.Dictionary")

d.Add Entity, Null
d.Add Project, Null <- Debugger highlights this row
d.Add Status, Null
d.Add Draft, Null
...

我试过的:
  • Casting the key, values as a string w/CSTR()
  • 最佳答案

    我的解决方案:

    将键添加为字符串,然后执行任何逻辑。然后,将字典中的值传递回要使用的变量。

    代码:

    Dim Entity As Variant
    Dim Project As Variant
    Dim Status As Variant
    Dim Draft As Variant
    ...
    
    Set d = CreateObject("Scripting.Dictionary")
    
    d.Add "Entity", Null
    d.Add "Project", Null
    d.Add "Status", Null
    d.Add "Draft", Null
    ...
    
    ' Pass the values into the variable after manipulation
    Entity = d("Entity")
    Project = d("Project")
    Status = d("Status")
    Draft = d("Draft")
    

    关于Excel VBA : This key is already associated with an element of this collection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47835179/

    相关文章:

    excel - 使窗口在后台打开

    excel - VBA中 "end"和 "exit sub"有什么区别?

    excel - VBA中的条件格式,基于函数

    excel - 创建表作为选择位置 - 使用当前数据库编译错误

    excel - 将数字添加到excel中的日期(平均值和标准差)

    python - "UnicodeEncodeError: ' charmap ' codec can' t 编码字符”尝试通过 openpyxl 解析 .xlsx 时

    .net - 这是为 COM 注册 .NET 类型的一种可能方法吗

    excel - 使用ADODB访问打开的xls文件

    arrays - 记录宏所做更改的最快方法

    excel - 如何从 VBA 更改列名