2017-01-03 141 views
0

我一直在嘗試學習如何在Excel VBA中創建自定義集合,並在MSDN上找到這段代碼。雖然我理解它的大部分,誰能告訴我最後的代碼Set Add = empNew在做什麼?我不明白這是評論。謝謝!VBA自定義集合對象

' 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 
+0

當你調用'Add()'方法時,這一行只是返回創建的'empNew' instanse結果。 – omegastripes

回答

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 
+0

謝謝!所以這意味着如果我不需要它返回任何值(或對象),我可以將此函數更改爲一個子對象?我想我現在明白了。 – yatsky

+0

這是正確的 - 不同的是,一個'Sub'不會返回任何東西,它基本上只是一個運行的程序,而一個'Function'返回任何被它調用的東西。 – Vegard

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 testEmp() 

Dim s As Employee 

s = Add("Shai", 50000) 

End Sub 

我在即時窗口中獲得s以下值:

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

我希望這是你在何意您的帖子。

+0

謝謝!這不是我的代碼,不完整,所以可能會有點混亂。我現在明白了。 – yatsky

+0

@yatsky如果我幫你解決了你的帖子中的問題,那麼標記爲「答案」 –

+0

我認爲Vegard的答案更像我追求的,但感謝你的幫助。 – yatsky