VBA自定义集合对象

时间:2017-01-03 07:13:58

标签: excel-vba vba excel

我一直在尝试学习如何在Excel VBA中创建自定义集合,我在MSDN上找到了这段代码。虽然我了解其中的大部分内容,但有人能告诉我最后一段代码Set Add = empNew正在做什么吗?我不理解它的评论。谢谢!

' Methods of the Employees collection class.
Public Function Add(ByVal Name As String, _
ByVal Salary As Double) As Employee
   Dim empNew As New Employee
   Static intEmpNum As Integer
   ' Using With makes your code faster and more
   ' concise (.ID vs. empNew.ID).
   With empNew
      ' Generate a unique ID for the new employee.
      intEmpNum = intEmpNum + 1
      .ID = "E" & Format$(intEmpNum, "00000")
      .Name = Name
      .Salary = Salary
      ' Add the Employee object reference to the
      ' collection, using the ID property as the key.
      mcolEmployees.Add empNew, .ID
   End With
   ' Return a reference to the new Employee.
   Set Add = empNew
End Function

2 个答案:

答案 0 :(得分:1)

您会注意到AddFunction的名称。通过发出Set Add = newEmp,您的代码声明函数的return value(或在此情况下为对象)是新创建的员工对象newEmp。这意味着该函数会将变量newEmp传递回其调用者。

假设你有一些程序调用你的函数,你就可以这样做:

Sub listEmployees
    Dim e As Employee

    ' Create a new employee, and assign the variable e to point to this object
    Set e = Add("John", 1000) ' Notice that the only reason we use "add" here is because it is the name of the function you provided

    ' e is now an Employee object, after being created in the line above, meaning we can access whatever properties is defined for it. The function Add lists some properties, so we can use those as examples.
    Debug.Print e.Name
    Debug.Print e.Salary
    Debug.Print e.ID
End Sub

答案 1 :(得分:0)

首先,您需要定义已创建的新Type,因此请将以下代码放在模块之上:

Public Type Employee
    id As String
    Name As String
    Salary As Long
End Type

然后,在Public Function Add内,更改为Dim empNew As Employee。 不确定为什么需要以下行:mcolEmployees.Add empNew, .id ??

,最后一行修改为Add = empNew

然后,当我从以下Sub测试此函数时:

Sub testEmp()

Dim s As Employee

s = Add("Shai", 50000)

End Sub

我在即时窗口中获取s以下值:

s.id = E00001
s.Name = "Shai"
s.Salary = 50000

我希望这是你在帖子中的意图。