虽然字典中的条目是单独创建的,但它们都具有相同的值

时间:2016-04-27 11:56:17

标签: excel excel-vba vba

我有1:n-Relationship

的Excel表格
ID  value
----------
1   A
1   B
1   C
2   A
2   B
3   F
4   X
4   Z

一个对象(CValueMap),它应该存储给定ID的值:

Option Explicit

Public id As Integer
Public values As Collection

我通过迭代行来读取excel表,创建CValueMap(如果它在我的字典中不存在)并填充值。

Dim idCell As Range
Dim allValues As New Scripting.Dictionary
allValues.RemoveAll

For Each idCell In Range("id_value_table[ID]")
    If Not allValues.Exists(idCell.value) Then
        Dim newValueMap As New CValueMap
        newValueMap.id = idCell.value
        Set newValueMap.values = New Collection
        allValues.Add idCell.value, newValueMap
    End If

    Dim valueMap As CValueMap
    Set valueMap = allValues.Item(idCell.value)
    valueMap.values.Add idCell.Offset(0, 1).value
Next idCell

我现在假设我有4个CValueMap s,其中第一个ABC,第二个AB,第三个F和最后XZ作为价值观。然而,这不是这种情况,因为此代码显示:

'iterate allValues
Dim singleKey as Variant
For Each singleKey In allValues.Keys
    Debug.Print singleKey & " has these values:"
    Debug.Print "ID: " & allValues.Item(singleKey).id
    Dim value As Variant
    For Each value In allValues.Item(singleKey).values
        Debug.Print "  " & value
    Next value
Next singleKey

---------------OUTPUT:-------------------
1 has these values:
ID: 4
  X
  Z
2 has these values:
ID: 4
  X
  Z
3 has these values:
ID: 4
  X
  Z
4 has these values:
ID: 4
  X
  Z

我不确定我哪里出错了。根据我假设相同 ValueMap可能已写入allValues词典中每个条目的行为,但因为我确实创建了4个不同的值并正确加载它们在添加value之前,我没有看到这可能发生的地方。

2 个答案:

答案 0 :(得分:2)

对象课程 - 从不使用Dim... As New...,因为您无法控制何时或是否获得新对象。

对所需代码进行简单更改:

Dim idCell                As Range
Dim allValues             As Scripting.Dictionary
Dim newValueMap           As CValueMap

Set allValues = New Scripting.Dictionary
allValues.RemoveAll

For Each idCell In Range("id_value_table[ID]")
    If Not allValues.Exists(idCell.value) Then
        Set newValueMap = New CValueMap
        newValueMap.id = idCell.value
        Set newValueMap.values = New Collection
        allValues.Add idCell.value, newValueMap
    End If

    Dim valueMap          As CValueMap
    Set valueMap = allValues.Item(idCell.value)
    valueMap.values.Add idCell.Offset(0, 1).value
Next idCell

答案 1 :(得分:0)

在结束之前如果,请添加以下行:

newFolder