類模組範圍例項化和重用

預設情況下,新的類模組是 Private 類,因此它僅可用於例項化並在定義它的 VBProject 中使用。你可以在同一個專案中的任何位置宣告,例項化和使用該類 :

'Class List has Instancing set to Private
'In any other module in the SAME project, you can use:

Dim items As List
Set items = New List

但是,你通常會編寫你希望在其他專案中使用的類,而無需在專案之間複製模組。如果你在 ProjectA 中定義一個名為 List 的類,並想在 ProjectB 中使用該類,那麼你需要執行 4 個動作:

  1. 在屬性視窗中更改 List 中 List 類的例項屬性,從 Private 到 PublicNotCreatable

  2. 在 ProjectA 中建立一個公共工廠功能,建立並返回 List 類的例項。通常,工廠函式將包含用於初始化類例項的引數。工廠函式是必需的,因為 ProjectB 可以使用該類,但是 ProjectB 不能直接建立 ProjectA 類的例項。

     Public Function CreateList(ParamArray values() As Variant) As List
         Dim tempList As List
         Dim itemCounter As Long
         Set tempList = New List
         For itemCounter = LBound(values) to UBound(values) 
             tempList.Add values(itemCounter)
         Next itemCounter
         Set CreateList = tempList
     End Function
    
  3. 在 ProjectB 中,使用 Tools..References... 選單新增對 ProjectA 的引用。

  4. 在 ProjectB 中,宣告一個變數並使用 ProjectA 的工廠函式為其分配一個 List 的例項

     Dim items As ProjectA.List
     Set items = ProjectA.CreateList("foo","bar")
    
     'Use the items list methods and properties
     items.Add "fizz"
     Debug.Print items.ToString()
     'Destroy the items object
     Set items = Nothing