2015-05-20 68 views
4

是否有可能(使用COM和regasm.exe)使vba函數調用vb.net函數 - 它在vb.net中創建類,然後將該類傳回vba,它被認爲是一個vba類?在VB.net中創建VBA類

在VBA中,我可以使用Insert> Class Module來處理類。我已經創建了一個創建類的函數。

Private length As Double 
Private height As Double 
Public Sub init(ByRef hgt As Double) 
    height = hgt 
    length = dbl_height() 
End Sub 

Public Function dbl_height() 
    dbl_height = height * 2 
End Function 

我可以相應地使用此功能初始化:

Public Function CreateClassFunction(foo As Integer) 
    Dim my_rect As Rectangle 
    Set my_rect = New Rectangle 
    my_rect.init (foo) 
    Set CreateClassFunction = my_rect 
End Function 

我也可以做同樣的事情在vb.net用幾乎相同的代碼。

Public Class Rectangle 
    Private length As Double 
    Private height As Double 
    Public Sub init(ByRef hgt As Double) 
    height = hgt 
    length = dbl_height() 
    End Sub 

    Public Function dbl_height() 
    dbl_height = height * 2 
    End Function 
End Class 

其中該vb.net函數創建類:

Public Function CreateClassFunction(foo As Integer) As Rectangle 
    Dim my_rect As Rectangle 
    my_rect = New Rectangle 
    my_rect.init(foo) 
    CreateClassFunction = my_rect 
End Function 

我可以在Variant /對象/矩形採用拉進VBA:

Function MyCreateClass(a As Double) 
    Dim classLib As New MyAnalytics.Class1 
    Set MyCreateClass = classLib.CreateClassFunction(a) 
End Function 

但是此對象不有高度或長度變量。 (報告說,監視窗口上的 「不變量」)

編輯:

每墊的馬克杯答案

修正代碼:

Public Class Rectangle 
Private plength As Double 
Private pheight As Double 
Public Property length() As Double 
    Get 
     Return plength 
    End Get 
    Set(ByVal value As Double) 
     plength = value 
    End Set 
End Property 

Public Property height() As Double 
    Get 
     Return pheight 
    End Get 
    Set(ByVal value As Double) 
     pheight = value 
    End Set 
End Property 

Public Sub init(ByRef hgt As Double) 
    height = hgt 
    length = dbl_height() 
End Sub 

Public Function dbl_height() 
    dbl_height = height * 2 
End Function 

End Class 

和測試VBA:

Function MyCreateClass(a As Double) 
    Dim classLib As New MyAnalytics.Class1 

    Set MyCreateClass = classLib.CreateClassFunction(a) 

    Debug.Print MyCreateClass.Height() 
    Debug.Print MyCreateClass.length() 

    MyCreateClass.Height = 30 
    MyCreateClass.length = 20 

    Debug.Print MyCreateClass.Height() 
    Debug.Print MyCreateClass.length() 

    MyCreateClass.init (100) 
    Debug.Print MyCreateClass.Height() 
    Debug.Print MyCreateClass.length() 


End Function 
+0

「長度」和「高度」屬性是私人的,因此它們不會暴露在課程之外。 – OneFineDay

+1

他們不是屬性,他們是領域。不要公開領域。永遠。 –

回答

2

它將不會被識別爲VBA類 - 它的不是一個VBA類,而是一個COM對象。

您的Rectangle班有私人領域。私人領域是,Private。這大致就是VBA所看到的:

Public Class Rectangle 
    Sub init(ByRef hgt As Double)  
    Function dbl_height() 
End Class 

這些字段在哪裏?

Private length As Double 
Private height As Double 

你沒有暴露他們 - 就VBA而言,他們不存在。

現在,你可以讓他們Public - 但你會打破封裝暴露領域; 不要那樣做!

揭露屬性獲取,而是和制定者,如果你想VBA代碼能夠改變一個Rectangle實例的LengthHeight性能。

+0

謝謝你@墊杯。在調試時是否可以在Watches窗口中看到屬性?它們可以在代碼和即時窗口中訪問。 –