Присвойте значение массиву - PullRequest
1 голос
/ 26 мая 2020

У меня есть dictionary, который также хранит array. Вот код, и я пытаюсь присвоить массиву какое-то значение. Но он всегда не может присвоить значение array. Как я могу это решить? Спасибо

Код:

Dim dict As Dictionary
Set dict = New Dictionary
For i = 1 To fruitList.count
    dict .Add fruitList(i), Array(0, 0, 0, 0, 0)
next
dict(apple)(0) = 100 //however, the first index in the array always equals to 0

Обновление: Или я должен спросить таким образом. Разве я не добавляю array как значение в dictionary неправильно?

Ответы [ 2 ]

1 голос
/ 26 мая 2020

Попробуйте:

Sub addArray2Dict()
    Dim a: a = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0) 'Here declare and store the array,
                                                   'you can do it any other way
                                                   'there is no difference if you do it here or
                                                   'in the loop
    Dim b 'Just for testing porpuse
    Dim oDict As Object 'Because I use “Microsoft Scripting Runtime” can use earle binding
    Set oDict = CreateObject("Scripting.Dictionary")
    Dim i 'iterator

    'Store numbers and letters inside the dictionary
    'BUT in the index number 5 I will store the array
    For i = 1 To 20
        If i = 5 Then
            oDict.Add i, a
           'oDict.Add i, Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0) 'As I said, this is the same as the line above.
        Else
            oDict.Add i, Chr(66 + i) 'Storing just letters in every key(integer)
        End If
    Next i

    b = oDict(5) 'Here I take the array from the Dictionary, and store it inside b,
    Debug.Print b(3) 'Here just print the 3th (number 4)  elemente of the array
                     'remember the array is:
                     '
                     ' array( 1 2 3 4 5 6 7 8 9 0 ) right!
                     '        0 1 2 3 4 5 6 7 8 9   <<< with that index
                     '
                     ' if i want the 3th value i will get the number 4 in my example.
End Sub

enter image description here

Используйте это как ссылку

«Microsoft Scripting Runtime» (добавить с помощью Tools-> References из меню VB)

Насколько я понимаю, ваш код может быть таким:

Sub Test()
    Dim fruitList(1 To 5) As String
    Dim i
    Dim B
    fruitList(1) = "apple"
    fruitList(2) = "banana"
    fruitList(3) = "melon"
    fruitList(4) = "orange" 'Love oranges!
    fruitList(5) = "kiwi" 'Love Kiwi too!!!!
    Dim dict As Dictionary 
    Set dict = New Dictionary 
    For i = LBound(fruitList) To UBound(fruitList) 'here you use the bounds of the array,
                                                   'instead .count, here won't work
        dict.Add fruitList(i), Array(0, 0, 0, 0, 0)
    Next
    B = dict("apple") '(0) = 100 'however, the first index in the array always equals to 0
    B(0) = 100 'Here! You take the array FROM the dictionary and store it inside B
               'Just do it!
    B(1) = 200
    B(2) = 300
    B(3) = 500
    B(4) = 1000000
    Debug.Print B(0) 'Testing! This will print in the console your value (100).
    dict.Remove "apple" 'Remove the array
    dict.Add "apple", B 'Return the new array!
End Sub

Вы не можете изменить значения массива, хранящегося внутри словаря (в VBA). Лучше убрать массив и изменить значения, а после этого, если нужно, сохранить обратно в dict.

Отметьте этот ответ Если Тим Уильямс говорит, что вы не можете, это потому, что никто не может!

0 голосов
/ 26 мая 2020

Все это можно найти здесь: https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/arrays/

Dim myArray(arraySize) As ArrayType

или

Dim myArray = New ArrayType() {Item1, Item2, ...}

Итак, на практике это должно выглядеть так:

Dim companies(3) as String
companies(0) = "Microsoft"
companies(1) = "Google"
companies(2) = "Amazon"

или:

Dim companies = New String() {"Microsoft", "Google", "Amazon"}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...