如何覆盖 scripting.dictionary 中键的值?

bar*_*icz 1 excel vba

我有以下 if 子句嵌套在 for 循环中:

    If status Like "*Active*" Then
        total_active = total_active + amount
        On Error Resume Next
        active_dict.Add Key:=cost_center, Item:=total_active
        On Error GoTo 0
    end if
Run Code Online (Sandbox Code Playgroud)

On Error Resume Next用于在将active_dict字典中已存在的键添加到其中时忽略错误。

问题是total_active键 ( cost_center)的值 ( )没有更新。

问题是:是否可以覆盖字典键的值?

Vin*_*t G 5

如果您使用 Microsoft Scripting Dictionary,则可以使用以下内容:

If status Like "*Active*" Then
    total_active = total_active + amount
    If active_dict.Exists(cost_center) Then
        active_dict(cost_center) = total_active
    Else
        active_dict.Add Key:=cost_center, Item:=total_active
    End If
End If
Run Code Online (Sandbox Code Playgroud)

甚至更好(见 Kostas K 评论):

If status Like "*Active*" Then
    total_active = total_active + amount
    active_dict(cost_center) = total_active
End If
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考,无需检查密钥是否存在。如果没有,无论如何都会添加它,一旦您引用它(如您的评论所示)。:) (2认同)