2012-12-11 43 views
9

我在類模塊到目前爲止使用let財產的理解是,你設置它的類模塊是這樣的:讓VBA類模塊的屬性 - 是否有可能有多個參數?

Dim pName as String 
Public Property Let Name(Value As String) 
    pName = Value 
End Property 

然後你你已經創建了這個類,你可以的對象後,設置該屬性,象這樣:

MyObject.Name = "Larry" 



問題:是否有可能以某種方式進入多個參數爲一個類的屬性?例如:

Dim pFirstName as String, pLastName as String 
Public Property Let Name(FirstName As String, LastName As String) 
    pFirstName = FirstName 
    pLastName = LastName 
End Property 

那麼您將如何去設置這個屬性以外的類?

MyObject.Name = ?? 

或者這僅僅是不可能做到的?

+1

單個屬性不能有兩個參數特爾斯,儘管你可以使用數組。在這種情況下,最好使用像SetName(first,last)這樣的常規Sub。 –

+0

謝謝。你確定它可以做一個數組嗎?當我嘗試的時候,我總是收到「不能分配給數組」的錯誤。 – mattboy

+0

@mattboy - 我已添加到我的答案中,向您展示如何使用所需的數據返回或更復雜的對象。 – InContext

回答

7

根據你的評論,如果你想要封裝這個邏輯,那麼你可以使用類似於下面的東西。

下面包含了子和函數。該函數返回一個Person對象:

Public Sub testing() 

    Dim t As Person 

    Set t = PersonData("John", "Smith") 

End Sub 


Public Function PersonData(firstName As String, lastName As String) As Person 

    Dim p As New Person 

    p.firstName = firstName 
    p.lastName = lastName 

    Set PersonData = p 

End Function 

Person類:

Dim pFirstName As String, pLastName As String 

Public Property Let FirstName(FirstName As String) 
    pFirstName = FirstName 
End Property 

Public Property Get FirstName() As String 
    FirstName = pFirstName 
End Property 

Public Property Let LastName(LastName As String) 
    pLastName = LastName 
End Property 

Public Property Get LastName() As String 
    LastName = pLastName 
End Property 
+1

謝謝,但我希望有一種方法來創建對象時創建對象而不是一行爲一行的所有內容,一個爲最後一個名稱和其他行可能需要的其他行。但我想你只是需要創建一個Sub而不是一個屬性來做到這一點。 – mattboy

+0

看我的編輯。我認爲它更好地用於調用返回Person類而不是子類的函數。你對字段和強類型都有智能感知。 – InContext

1

用作公共Sub過程的類內執行此:

Public Sub testing() 
Dim myPerson As New Person 
myPerson.SetName "KaciRee", "Software" 

End Sub 

Person類:

Dim pFirstName As String, pLastName As String 

Public Property Let FirstName(FirstName As String) 
    pFirstName = FirstName 
End Property 

Public Property Get FirstName() As String 
    FirstName = pFirstName 
End Property 

Public Property Let LastName(LastName As String) 
    pLastName = LastName 
End Property 

Public Property Get LastName() As String 
    LastName = pLastName 
End Property 

Public Sub SetName(FirstName As String, LastName As String) 
pFirstName = FirstName 
pLastName = LastName 
End Sub 
相關問題