我需要在VBA scripting.dictionary中交换条目。为什么这段代码失败了?
Code: `Option Explicit
Sub playWithGroup()
Dim Data As Object
Dim msg As String
Dim k As Variant
Dim i As Integer
Set Data = CreateObject("Scripting.Dictionary")
Data.Add key:="a", Item:="A"
Data.Add key:="b", Item:="B"
Data.Add key:="c", Item:="C"
Data.Add key:="d", Item:="D"
Data.Add key:="e", Item:="E"
Data.Add key:="f", Item:="F"
For i = 0 To Data.count - 1
Debug.Print Data.keys()(i) & " " & Data.items()(i)
Next i
Debug.Print ""
k = Data.keys()(1)
Data.keys()(1) = Data.keys()(3)
Data.keys()(3) = k
Debug.Print "k: " & k
For i = 0 To Data.count - 1
Debug.Print Data.keys()(i) & " " & Data.items()(i)
Next i
Debug.Print ""
End Sub
立即窗口中的输出:
a A
b B
c C
d D
e E
f F
k: b
a A
b B
c C
d D
e E
f F
`
答案 0 :(得分:1)
Keys() method返回包含键的数组。您正在修改此返回的数组,然后立即丢弃该数组,从而修改它。每次调用Keys()
都会返回一个全新的数组,该数组基于未修改的字典。
要交换字典中的元素,最自然的方法是直接使用键:
k = Data("b")
Data("b") = Data("d")
Data("d") = k