2017-01-03 5 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'インスタンスを返します。 – 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からこの関数をテストする場合:

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

ベガードの答えは私が追いかけているものに近いと思いますが、あなたの助けに感謝します。 – yatsky

関連する問題