new*_*ion 5 arrays excel vba dictionary
我想用一个项目的几个属性填充一个字典。例子:
我正在考虑将Item 1和Item 2作为Dictionary键,并带有一个array可以保存其属性的键。我需要能够分别访问一个项目的每个属性,因此将它们连接为一个字符串不是一种选择。
我正在考虑类似下面的伪代码:
With Workbooks("testing macro").Sheets(test).Range("D7:G8")
For i = 1 To .Rows.count
items_dict.Add Key:=.Cells(i, 1).Value, _
Item:= array(i,1)= .cells(i,2).value array(i,2)=.cells(i,3).value array(i,3).cells(i,4)
Run Code Online (Sandbox Code Playgroud)
这是一个使用类和集合的简单示例(基本上是根据此处的示例进行修改的:
类非常简单(类名是 Employee):
Option Explicit
Private pName As String
Private pAddress As String
Private pSalary As Double
Public Property Get Name() As String
Name = pName
End Property
Public Property Let Name(Value As String)
pName = Value
End Property
Public Property Get Address() As String
Address = pAddress
End Property
Public Property Let Address(Value As String)
pAddress = Value
End Property
Public Property Get Salary() As Double
Salary = pSalary
End Property
Public Property Let Salary(Value As Double)
pSalary = Value
End Property
Run Code Online (Sandbox Code Playgroud)
这是测试代码:
Option Explicit
Sub test()
Dim counter As Integer
Dim Employees As Collection
Dim Emp As Employee
Dim currentEmployee As Employee
Set Employees = New Collection
For counter = 1 To 10
Set Emp = New Employee
Emp.Name = "Employee " & counter
Emp.Address = "Address " & counter
Emp.Salary = counter * 1000
Employees.Add Emp, Emp.Name
Next counter
Set currentEmployee = Employees.Item("Employee 1")
Debug.Print (currentEmployee.Address)
End Sub
Run Code Online (Sandbox Code Playgroud)
如您所见,我正在向我的类添加指定键的项目:
Employees.Add Emp, Emp.Name
Run Code Online (Sandbox Code Playgroud)
然后您可以使用它直接拉取而不需要循环。