2012-03-23 66 views
13

我希望能夠以初始化VBA:用值初始化對象?

CArticle具有下列性質:

Private pNumber As String 
Private pQuantity As Double 

與任一空的,預先定義的值或電流值。我怎樣才能做到這一點?我沿線的思考的東西:

新的空CArticle

pNumber 
pQuantity 

新的虛擬CArticle

pNumber 
pQuantity = 99999 

新初始化CArticle(number, quantity)

pNumber = number 
pQuantity = quantity 
+0

的[傳遞函數參數構造函數,VBA(可能的複製https://stackoverflow.com/questions/15224113/pass- arguments-to-constructor-in-vba) – Roland 2017-10-04 15:36:12

回答

15

它是一個痛苦脖子,但這是做到這一點的唯一方法。

文件CArticle

Option Explicit 

Private pNumber As String 
Private pQuantity As Double 

Private Sub Class_Initialize() 
    pNumber = vbNullString 
    pQuantity = 0 
End Sub 

Public Sub InitializeWithValues(ByVal number As String, ByVal quantity As Double) 
    pNumber = number 
    pQuantity = quantity 
End Sub 

Public Sub InitializeDefaultValues() 
    pNumber = vbNullString 
    pQuantity = 99999 
End Sub 

,並調用模塊中

Dim art As New CArticle  ' Initialize value to empty 
art.InitializeWithValues "Bowtie", 100  ' and assign values 

Set art = New CArticle  ' Initialize values to empty 
art.InitializeDefaultValues ' Initialize values to default 
+2

爲了從工作表中提取值,創建'InitializeFromRange(ByVal r as Range)'方法可能很有用。 – ja72 2015-01-18 16:03:45