gpt4 book ai didi

vba - 使用字典类型的另一个变量初始化字典类型的一个变量时出现问题

转载 作者:行者123 更新时间:2023-12-03 03:11:15 24 4
gpt4 key购买 nike

Dim globalDict
Dim localDict
.
'Data from a excel is loaded to globalDict

Set localDict=globalDict(1)

localDict(item1)="AAA"

此更新还更新了 globalDict 中的值。就好像 localDict 只是一个指针。

知道可能出了什么问题吗?

谢谢,拉杰什

最佳答案

这是设计使然:请参阅 Set StatementStatements (VBScript) :

Generally, when you use Set to assign an object reference to a variable, no copy of the object is created for that variable. Instead, a reference to the object is created. More than one object variable can refer to the same object. Because these variables are references to (rather than copies of) the object, any change in the object is reflected in all variables that refer to it.

您可以按如下方式制作 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
-

关于vba - 使用字典类型的另一个变量初始化字典类型的一个变量时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37644677/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com