似乎大多数答案都与C#有关,所以我觉得比较安全:
我需要按其值调用字典键。我有一个包含四个字符键列表的字典对象。例如:
dSCAC.Add "AAAA", 1
dSCAC.Add "BBBB", 2
dSCAC.Add "CCCC", 3
dSCAC.Add "DDDD", 4
等
在字符串(在本例中为电子邮件主题行)中找到与键相关联的值时,我已经能够调用它,然后从该值中添加或删除1。
例如:检测到BBBB,值为2。修改该值并调用相应的键。在这种情况下,最后我们要varOtherSCAC = AAAA。
If dSCAC(varSCAC) Mod 2 Then
Debug.Print "Odd " & "PAPS"
varOtherSCAC = (dSCAC(varSCAC) + 1)
Debug.Print "Opposite SCAC is " & varOtherSCAC
Else
Debug.Print "Even " & " PARS"
varOtherSCAC = (dSCAC(varSCAC) - 1)
Debug.Print "Opposite SCAC is " & varOtherSCAC
End if
我无法根据此值确定调用新密钥的语法。在VBA中甚至可能吗?有办法解决吗?
答案 0 :(得分:1)
我将采用与@TateGarringer相似的方法,但是将两个Dictionary
对象包装在一个类中,以为它们提供一个通用的接口,并使事情更易于使用:
'In a class module named MirroredDictionary.cls (add reference to Scripting Runtime)
Option Explicit
Private backing As Scripting.Dictionary
Private mirror As Scripting.Dictionary
Private Sub Class_Initialize()
Set backing = New Scripting.Dictionary
Set mirror = New Scripting.Dictionary
End Sub
Public Sub Add(Key As Variant, Value As Variant)
backing.Add Key, Value
mirror.Add Value, Key
End Sub
Public Function KeyExists(Key As Variant) As Boolean
KeyExists = backing.Exists(Key)
End Function
Public Function ValueExists(Value As Variant) As Boolean
ValueExists = mirror.Exists(Value)
End Function
Public Function ValueFromKey(Key As Variant) As Variant
ValueFromKey = backing.Item(Key)
End Function
Public Function KeyFromValue(Value As Variant) As Variant
KeyFromValue = mirror.Item(Value)
End Function
取决于您打算如何使用它,您可能会或可能不希望包装其他功能。用法与普通的Dictionary
类似(除了属性名称有所不同,尽管您可以更改其口味):
Public Sub Example()
Set sample = New MirroredDictionary
sample.Add "AAAA", 1
sample.Add "BBBB", 2
sample.Add "CCCC", 3
sample.Add "DDDD", 4
Debug.Print sample.ValueFromKey("AAAA") '1
Debug.Print sample.KeyFromValue(1) 'AAAA
Debug.Print sample.ValueFromKey("BBBB") '2
Debug.Print sample.KeyFromValue(2) 'BBBB
Debug.Print sample.ValueFromKey("CCCC") '3
Debug.Print sample.KeyFromValue(3) 'CCCC
Debug.Print sample.ValueFromKey("DDDD") '4
Debug.Print sample.KeyFromValue(4) 'DDDD
End Sub
答案 1 :(得分:0)
您始终可以创建其他字典来存储Key-Value
对与Value
作为key
和key
作为value
Sub test()
Dim dSCAC As Object
Dim dSCACArr As Object
Dim varOtherSCAC As String
Dim key
Dim varSCAC
Set dSCAC = CreateObject("Scripting.Dictionary")
Set dSCACArr = CreateObject("Scripting.Dictionary")
dSCAC.Add "AAAA", 1
dSCAC.Add "BBBB", 2
dSCAC.Add "CCCC", 3
dSCAC.Add "DDDD", 4
For Each key In dSCAC.Keys
dSCACArr.Add dSCAC(key), key
Next
For Each varSCAC In dSCAC.Keys
If dSCAC(varSCAC) Mod 2 Then
Debug.Print "Odd " & "PAPS"
varOtherSCAC = dSCACArr(dSCAC(varSCAC) + 1)
Debug.Print "Opposite SCAC is " & varOtherSCAC
Else
Debug.Print "Even " & " PARS"
varOtherSCAC = dSCACArr(dSCAC(varSCAC) - 1)
Debug.Print "Opposite SCAC is " & varOtherSCAC
End If
Next
End Sub
这产生了结果
Odd PAPS
Opposite SCAC is BBBB
Even PARS
Opposite SCAC is AAAA
Odd PAPS
Opposite SCAC is DDDD
Even PARS
Opposite SCAC is CCCC
编辑:
For Each varSCAC In dSCAC.Keys...Next
仅用于概念验证。