Dim globalDict
Dim localDict
.
'Data from a excel is loaded to globalDict
Set localDict=globalDict(1)
localDict(item1)="AAA"
此更新也会更新globalDict
中的值。它好像localDict
只是一个指针。
知道可能出现什么问题吗?
谢谢, 拉杰什
答案 0 :(得分:5)
按设计进行操作:请参阅Set Statement下的Statements (VBScript):
通常,当您使用
Set
将对象引用分配给a时 为该变量创建变量没有对象的副本。 而是创建对象的引用。超过一个 对象变量可以引用同一个对象。因为这些变数 是对象的引用(而不是副本),对象的任何改变 该对象反映在引用它的所有变量中。
您可以按如下方式制作 Dictionary 对象的相同副本:
option explicit
On Error GoTo 0
Dim strResult: strResult = Wscript.ScriptName
Dim globalDict
Set globalDict = CreateObject("Scripting.Dictionary")
globalDict.Add "a", "Athens" ' add some keys and items
globalDict.Add "b", "Belgrade"
globalDict.Add "c", "Cairo"
' create an identical copy of a Dictionary object
Dim localDict, arrKeys, arrItems, ii ' declare variables
Set localDict = CreateObject("Scripting.Dictionary")
arrKeys = globalDict.Keys ' get the keys
'arrItems = globalDict.Items ' get the items: unnecessary
For ii= 0 To UBound( arrKeys)
'(debug output) strResult = strResult & vbNewLine & arrKeys(ii) & vbTab & arrItems(ii)
localDict.Add arrKeys(ii), globalDict( arrKeys(ii)) ' add appropriate keys and items
Next
' identical copy is created now
localDict("b") = "Brno"
strResult = strResult & vbNewLine & globalDict("b")
strResult = strResult & vbNewLine & localDict("b")
strResult = strResult & vbNewLine & "-"
'strResult = strResult & vbNewLine &
Wscript.Echo strResult ' the only `Echo` => run under `CScript.exe` or `WScript.exe`
<强>输出强>:
==> cscript D:\VB_scripts\SO\37644677.vbs
37644677.vbs
Belgrade
Brno
-