Unable to properly loop through keys AND values in

2019-07-27 22:11发布

问题:

I'm making a program in VB6, and I can't properly loop through a String dictionary.

I've tried both ways of accesssing a value in the collection. Collection(Key), and 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

The string in NetRcv is the following:

BLK modeswitch
mode codeslave
BND

I expect to see this sequence of MsgBoxes ...

modeswitch
mode
codeslave

... with possibly trailing spaces somewhere. I see the first two, and then it errors with

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

I don't understand why this error occurs.

member is the key, correct?

If it is, then there's no reason this error should pop up.

回答1:

For one thing, you have inverted the value and key. This:

thismsg.Add key, value

should be this:

thismsg.Add value, key

See here for the docos on the Add method

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



标签: foreach vb6