Excel字典具有多个值?

在Python中,我习惯于拥有像defaultdict这样的东西,我可以将多个值附加到给定的键上。 在Excel中,如果我从脚本运行时使用Dictionary对象,我只能为每个键添加一个项目。

有没有办法我可以这样做:

  1. 如果字典缺less密钥,则在dict [key]下添加List(第一项)
  2. 如果字典有密钥,则在dict [key]下追加项目到预先存在的列表

我希望我已经清楚了。 也许而不是一个列表我的意思是一个数组,不知道。

尝试:

Dim collect As New collection If Not dict.Exists(key) Then dict.Add key, collect End If collect = dict.Item(key) collect.Add (val) dict.Item(key) = collect 

您缺lessVBA中要分配给对象的Set关键字。 不pipe怎样,你可以用更简洁的格式绕过它们:

 If Not dict.Exists(Key) Then dict.Add Key, New Collection dict.Item(Key).Add Val 

如果你想保持你的旧格式,那么这是如何:

  Dim collect As New collection If Not dict.Exists(key) Then dict.Add key, collect End If Set collect = dict.Item(key) collect.Add (val) Set dict.Item(key) = collect 

但上面更紧凑的格式也可以正常工作。