Ehu*_*udz 2 excel vba dictionary
我需要在字典中的特定键和项对之后添加一个项目.基本上与添加成员在集合中允许的行为相同:(Collection.Add (item [,key] [,before] [,after])
Dictionary对象没有内置的方法允许这样做.这是一个快速推出自己的方法.这将特别实现您的要求,但修改起来应该很简单:
Function DictAdd(StartingDict As Dictionary, Key, Item, AfterKey) As Dictionary
Dim DictKey As Variant
Set DictAdd = New Dictionary
For Each DictKey In StartingDict
DictAdd.Add DictKey, StartingDict(DictKey)
If DictKey = AfterKey Then DictAdd.Add Key, Item
Next DictKey
End Function
Run Code Online (Sandbox Code Playgroud)
并测试它运行以下过程:
Sub TestDictAdd()
Dim MyDict As New Dictionary, DictKey As Variant
MyDict.Add "A", "Alpha"
MyDict.Add "C", "Charlie"
Set MyDict = DictAdd(MyDict, "B", "Bravo", "A")
For Each DictKey In MyDict
Debug.Print DictKey, MyDict(DictKey)
Next DictKey
End Sub
Run Code Online (Sandbox Code Playgroud)
这只是为了让你开始.如果我自己这样做,我可能会创建自己的自定义类来使用并创建自定义的Add方法而不是使用函数.我还会做出以下改进: