是否有可能(使用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拉入vba:
Function MyCreateClass(a As Double)
Dim classLib As New MyAnalytics.Class1
Set MyCreateClass = classLib.CreateClassFunction(a)
End Function
但是,此对象没有高度或长度变量. (它在观察窗口上显示“无变量”)
编辑:
修改后的代码根据Mat的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
最佳答案 它不会被识别为VBA类 – 它不是VBA类,而是COM对象.
您的Rectangle类具有私有字段.私人领域,私人领域.这大致是VBA所看到的:
Public Class Rectangle
Sub init(ByRef hgt As Double)
Function dbl_height()
End Class
田地在哪里?
Private length As Double
Private height As Double
你还没有暴露它们 – 就VBA而言,它们并不存在.
现在,你可以将它们公之于众 – 但是你会通过暴露字段打破封装;不要那样做!
如果希望VBA代码能够更改Rectangle实例的Length和Height属性,请改为展示属性getter和setter.