带复合键的VBA字典

时间:2015-04-07 02:31:56

标签: vba dictionary tuples

VBA中是否有允许使用元组作为键的结构,类似于Python?我希望在关联数组中存储一个大的值矩阵,并在两个维度中按键名称索引。

编辑:

以下是一个简单数据表的示例:


+--------+--------+--------+--------+--------+
|        | City 1 | City 2 | City 3 | City 4 |
+--------+--------+--------+--------+--------+
| City 1 |    0   |   7    |    8   |    6   |
| City 2 |        |   0    |    1   |    6   |
| City 3 |        |        |    0   |    5   |
| City 4 |        |        |        |    0   |
+--------+--------+--------+--------+--------+

我希望能够将这些值存储在关联数组(字典)中,因为在我的脚本执行过程中它们将被读取数百万次。我希望能够将字典键设为元组。因此,我想创建一个字典(我们称之为距离),键和值是:

(City 1, City 2) = 7
(City 1, City 3) = 8
(City 1, City 4) = 6
(City 2, City 3) = 1
(City 2, City 4) = 6
(City 3, City 4) = 5

我可以通过以下方式访问城市1和城市2之间的距离:

Distance("City 1", "City 2")

1 个答案:

答案 0 :(得分:0)

如果您使用的是Excel,我建议您使用一个函数,在任何单元格中,您都可以通过=Distance("ct1","ct2")等简单的fornula找到您的价值:

功能是:

Public Function Distance(RowCity As String, ColCity As String) As String
    Dim RowNo As Long, ColNo As Long
    RowNo = 0: ColNo = 0

    On Error Resume Next
    With ActiveSheet
        RowNo = .Columns("A").Find(What:=RowCity).Row
        ColNo = .Rows(1).Find(What:=ColCity).Column

        If RowNo <> 0 And ColNo <> 0 Then
            Distance = Trim(.Cells(RowNo, ColNo).Value & " ")
        Else
            Distance = "#N/A"
        End If
    End With
End Function
  

注意:当您使用Excel时,Excel工作表是二维数组,有许多您需要的选项。


您可以使用某种字典(来自COM对象):

Dim dict As Object
Dim key As Variant

Set dict = CreateObject("Scripting.Dictionary")

dict.Add "City 1", "City 2"

For Each key In dict.Keys
    If key = condiction Then
        'use dict.Item(key)
    End If
Next key