【问题标题】:Unable to properly loop through keys AND values in a VB6 For Each loop无法正确循环遍历 VB6 For Each 循环中的键和值
【发布时间】:2019-07-18 00:22:03
【问题描述】:

我正在用 VB6 编写程序,但无法正确循环字符串字典。

我已经尝试了两种访问集合中值的方法。 Collection(Key)Collection.Item(Key)

Dim line As Variant
Dim thismsg As New Collection
Dim thissection As String
For Each line In Split(NetRcv, vbLf)
    If Left(line, 3) = "BLK" Then
        thissection = Right(line, Len(line) - 3)
        MsgBox thissection
        GoTo nctlrParseLoopNext
    End If
    If Left(line, 3) = "BND" Then
        Exit For
    End If
    Dim key, value As String
    key = Left(line, InStr(line, " "))
    value = Right(line, InStr(line, " "))
    thismsg.Add key, value
nctlrParseLoopNext:
Next line
Dim member As Variant
For Each member In thismsg
    MsgBox member
    MsgBox thismsg(member)
Next member

NetRcv 中的字符串如下:

BLK modeswitch
mode codeslave
BND

我希望看到这个 MsgBoxes 序列...

modeswitch
mode
codeslave

...某处可能有尾随空格。 我看到前两个,然后它出错了

Run-time error '5':
Invalid procedure call or argument

我不明白为什么会出现这个错误。

member关键,对吗?

如果是,则没有理由弹出此错误。

【问题讨论】:

  • Collection 不是字典。请改用Scripting.DictionaryCollection 内部是一个链表。
  • 你想要一个字典使用的例子吗?
  • 就我个人而言,我从来没有使用过Collection。它的主要优势 - 收集异构对象的能力通常是它的另一个弱点,包括你的情况。坚持使用数组或 Scripting.Dictionary。
  • 我是恐龙编码员,我讨厌“goto”几十年来我第一次看到有人使用它。
  • @AdamRyczkowski CollectionItemO(N) 仅用于整数索引。对于字符串键访问它是O(log N)For Each 枚举是O(1)。 .Net 框架中没有等效的容器,但我们主要像 Dictionary<string, object> 一样使用它,并且从不通过索引访问它,因此性能(和内存使用)远远优于 Scripting.Dictionary 对应的容器。

标签: foreach vb6


【解决方案1】:

一方面,您已经颠倒了值和键。这个:

thismsg.Add key, value

应该是这样的:

thismsg.Add value, key

请参阅此处以获取有关 Add 方法的文档

https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/add-method-visual-basic-for-applications

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    • 2023-01-13
    • 2013-10-15
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多