ms-access - VBA - 嵌套类
问题描述
[编辑代码]对不起新手问题。我试图在 VBA for Excel 中测试嵌套类,但收到错误消息。谁能帮我理解为什么?谢谢!
课内:
' CLASS MODULE - cInside
' Member variables
Private m_Value As Integer
' Properties
Property Get Value() As Integer
Value = m_Value
End Property
Property Let Value(i As Integer)
m_Value = i
End Property
' Methods
Sub init()
m_Value = 0
End Sub
Sub Inc()
m_Value = m_Value + 1
End Sub
课外:
' CLASS MODULE - cOutside
' Member variables
Private m_Num1 As New cInside
Private m_Num2 As New cInside
' Properties
Property Get Num1() As cInside
Num1 = m_Num1.Value
End Property
Property Get Num2() As cInside
Num2 = m_Num2.Value
End Property
Property Set Num1(i As cInside)
Set m_Num1 = i
End Property
Property Set Num2(i As cInside)
Set m_Num2 = i
End Property
主程序:
Sub Main()
Dim o As New cOutside
Dim i As New cInside
i.Value = 9
i.Inc
Debug.Print i.Value '<-- this works
Set o.Num1 = i
o.Num1.Inc '<-- object variable or with block variable not set
Debug.Print (o.Num1.Value)
End Sub
再次感谢你!
解决方案
n.Num1
返回 an Integer
,它不是 的实例cInside
,因此没有Inc
成员,这使其成为编译器抱怨的无效限定符;-)
您的cOutside
班级需要以某种方式公开它:
Property Get ComposedObject1() As cInside
Set ComposedObject1 = m_Num1
End Property
然后调用代码可以这样做:
n.ComposedObject1.Inc
我称其为“组合”,因为您所做的不是“嵌套”,而是“组合”。VBA 不支持嵌套类,它是在另一个类模块中定义的类模块,如下所示:
Class Outside
'... members...
Class Inside
'...members...
End Class
End Class
VB.NET 可以做到这一点,但在 VBA 1 类模块中只能定义 1 个类。
推荐阅读
- excel - 使用 VBA 限制 Excel 中的地理定位 API 调用。
- python - Seaborn 没有改变 facetgrid 的线图方面的数据
- jquery - JQuery 重置函数 $('#form').get(0).reset(); 不在模式弹出按钮上工作?
- .net - Can't load Assembly System.Net.Http.Formatting in .Net 解决方案
- python-3.x - 匹配模式并填充 csv 文件
- python - print('Hello World!') 在 Python 代码中不使用 'e' 和 'p'
- netbeans - Netbeans 功能区在启动时禁用
- django - Django ModelChoiceField 验证错误
- angular - 如何使用 webpack 忽略打字稿错误?
- r - RStudio 探索性因子分析:编写一个提取越来越多因子的函数