是否有可能(使用COM和regasm.exe)让vba函数调用vb.net函数 - 它在vb.net中创建类,然后将类传递回vba,在那里它被识别为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 / Object / Rectangle拉入vbaFunction MyCreateClass(a As Double)
Dim classLib As New MyAnalytics.Class1
Set MyCreateClass = classLib.CreateClassFunction(a)
End Function
但是此对象没有高度或长度变量。 (它在观察窗口上显示“无变量”)
编辑:
根据Mat's Mug答案修改后的代码:
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 :(得分: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代码能够更改Length
实例的Height
和Rectangle
属性,请改为展示属性getter和setter。