VBA collection: list of keys

Class KeyValue:

Public key As String 
Public value As String 
Public Sub Init(k As String, v As String) 
    key = k 
    value = v 
End Sub 

Then to use it:

Public Sub Test() 
    Dim col As Collection, kv As KeyValue 
    Set col = New Collection 
    Store col, "first key", "first string" 
    Store col, "second key", "second string" 
    Store col, "third key", "third string" 
    For Each kv In col 
        Debug.Print kv.key, kv.value 
    Next kv 
End Sub 
 
Private Sub Store(col As Collection, k As String, v As String) 
    If (Contains(col, k)) Then 
        Set kv = col(k) 
        kv.value = v 
    Else 
        Set kv = New KeyValue 
        kv.Init k, v 
        col.Add kv, k 
    End If 
End Sub 
 
Private Function Contains(col As Collection, key As String) As Boolean 
    On Error GoTo NotFound 
    Dim itm As Object 
    Set itm = col(key) 
    Contains = True 
MyExit: 
    Exit Function 
NotFound: 
    Contains = False 
    Resume MyExit 
End Function 

This is of course similar to the Dictionary suggestion, except without any external dependencies.

The class can be made more complex as needed if you want to store more information.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值