Excel 从VBA字典中提取数组
我无法找到如何在VBA字典中存储和访问数组 我有一把钥匙,上面有多个项目,比如“苹果”,值为“3”,数量为“5” 一个项目不会有问题,即:dict(“苹果”)=3 但是如何存储和检索多个值呢?假设我想添加“苹果,3,5”,然后移动到单元格C4,并自动将苹果粘贴到那里,3在C5中,5在C6中 到目前为止,我已经尝试:Excel 从VBA字典中提取数组,excel,vba,dictionary,Excel,Vba,Dictionary,我无法找到如何在VBA字典中存储和访问数组 我有一把钥匙,上面有多个项目,比如“苹果”,值为“3”,数量为“5” 一个项目不会有问题,即:dict(“苹果”)=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 las
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=Items(2)放在消息框上方并引用它。我无法从字典中检索的数组中提取任何类型的信息。似乎Items=dict(sFruit)不是检索数组的方法。如果将
Items
作为变量进行调暗,并使用数组()
,应该可以使用
这只是一个示例,而不是您的代码
Sub testdict()
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
dict.Add "apple", Array(1, 3)
dict.Add "orange", Array(2, 5)
Dim k As Variant
Dim i As Long
Dim vals As Variant
For Each k In dict
vals = dict(k) 'set a variant to an array
Debug.Print vals(1) 'print the second element
For i = LBound(dict(k)) To UBound(dict(k)) 'iterate through all array elements
Debug.Print k, dict(k)(i) 'print everything in the dict
Next i
Next k
End Sub
与上一个问题完全相同:。编辑你的问题以改进它,然后它可以重新打开,它关闭是有原因的。嗨,Wolfie,它被编辑了,但没有重新打开。因此,我发布了一个新问题。你必须等待它重新打开,等待审核,这取决于你的编辑是否足够。你只有一个数组
项
,但你要将它添加到每个字典键的值中?解释您的数据是什么以及代码应该实现什么将有很大帮助。