Excel VBA字典中的数组引用
我无法找到如何在VBA字典中存储和访问数组 我有一把钥匙,上面有很多东西,比如苹果,价值3,数量5 单个项目不会成为问题,即: 苹果=3 但是如何存储和检索多个值呢? 假设我想添加苹果,3,5,然后移动到C4单元,自动将苹果粘贴在那里,3在C5中,5在C6中 到目前为止,我已经尝试:Excel VBA字典中的数组引用,excel,vba,dictionary,Excel,Vba,Dictionary,我无法找到如何在VBA字典中存储和访问数组 我有一把钥匙,上面有很多东西,比如苹果,价值3,数量5 单个项目不会成为问题,即: 苹果=3 但是如何存储和检索多个值呢? 假设我想添加苹果,3,5,然后移动到C4单元,自动将苹果粘贴在那里,3在C5中,5在C6中 到目前为止,我已经尝试: Dim last_row As Long last_row = Cells(Rows.Count, 1).End(xlUp).Row Dim last_col As Long last_col = ActiveSh
Dim last_row As Long
last_row = Cells(Rows.Count, 1).End(xlUp).Row
Dim last_col As Long
last_col = ActiveSheet.UsedRange.Columns.Count
Dim strVal As String
Dim Item(0 To 99) As String
Dim header As Range
Dim rng As Range
For Each rngCell In Range(Cells(1 + i, 1), Cells(last_row, 1))
i = i + 1
strVal = rngCell.Text
If Not dict.Exists(strVal) Then
n = 0
For Each headerCell In Range(Cells(i, 2), Cells(i, last_col))
n = n + 1
Item(n) = headerCell.Text
'MsgBox headerCell.Text
Next headerCell
dict(strVal) = Item
Else
MsgBox "already exists"
End If
Next rngCell
Dim Items(0 To 99) As String
sFruit = InputBox("Check value of key")
Items = dict(sFruit)
MsgBox "The value of " & sFruit & " is " & Items(2)
这是最后一个不起作用的部分。无论我是将项声明为变量、字符串或对象,还是将Item=Items2放在消息框上方并引用它。我无法从从字典中检索到的数组中提取任何类型的信息。下面是一个如何将数组写入字典以及以后如何访问它们的示例
Option Explicit
Public Sub DictArrayExample()
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
'create an array
Dim Arr() As Variant
Arr = Array("Item1", "Item2", "Item3") 'Array Index 0 to 2
'write the array into dictionary
dict.Add "apples", Arr
'or directly into dictionary without variable
dict.Add "bananas", Array("banana1", "banana2")
'directly access array inside dictionary
Debug.Print dict("apples")(1) 'index 1 = Item2
'get the array from the dictionary into another variable
Dim RetrieveArr() As Variant
RetrieveArr = dict("apples")
'access array in that variable
Debug.Print Join(RetrieveArr, ", ")
Debug.Print RetrieveArr(0) 'index 0 = Item 1
End Sub
使用dict.Add Apples,Array3,5来存储数组,而不是dict Apples=3。要将其放入单元格中,您需要编写具有所需逻辑的代码。有关词典的良好资源,请参阅。请注意,SO不是免费的代码编写服务,所以请自己尝试一下,如果遇到问题或错误,请返回您的代码或a。我更新了问题。我一直在跟保罗·凯利的向导学习。通常数组不会给我带来麻烦,除非它存储在字典中。似乎Items=dictsFruit不是检索数组的方法。请查看我的答案,如果这对您有帮助的话。