gpt4 book ai didi

vba - Scripting.Dictionary 在不使用 Dictionary.Add 的情况下添加项目 - BUG?

转载 作者:行者123 更新时间:2023-12-02 07:42:49 24 4
gpt4 key购买 nike

当您查找值时,Scripting.Dictionary 喜欢无缘无故地添加值!通过 30 秒的示例进行演示:

创建一个新工作表,并填写A1:A4 = {1,2,3,4}

插入新的 vba 模块并添加此代码

Public Sub test()

Dim rowIndex As Integer
'
Dim dict As Scripting.Dictionary
Set dict = New Scripting.Dictionary

For rowIndex = 1 To 4

dict.Add Trim(Sheet1.Cells(rowIndex, 1).Value), rowIndex

Dim notEvenAddingSoWhyAreYouAdding As Variant
notEvenAddingSoWhyAreYouAdding = dict(Sheet1.Cells(rowIndex, 1).Value)

Next rowIndex

End Sub

Next rowIndex上放置断点

运行子程序并检查dict的值。它现在有两个值:"1"1,如下图所示:

enter image description here

什么。这。见鬼?!

我意识到我在 dict.Add() 行中有 Trim(...) 函数,这意味着使用了两个不同的键,但为什么它在查找时是否会添加额外的值?!这毫无意义 - 现在 dict.Count 不会给出我期望的值。

最佳答案

正如您所指出的,您有两个不同的键,1"1"。如果您尝试访问字典中尚不存在的键,它会自动添加它。这是奇怪的行为。

我会使用这样的东西:

If dict.Exists(something) Then
myVariable = dict.Item(something)
End If

关于vba - Scripting.Dictionary 在不使用 Dictionary.Add 的情况下添加项目 - BUG?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48928316/

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