gpt4 book ai didi

excel - 正确编码构造函数

转载 作者:行者123 更新时间:2023-12-02 22:26:32 30 4
gpt4 key购买 nike

我正在尝试在 VBA excel 中实现模型- View -演示者用户界面。为了做到这一点,我一直在编写不同的模型类。这是一个例子:

Option Explicit

Private Type TModel
FilterCol As Collection
N As Integer
End Type

Private this As TModel

Public Property Get FilterCol() As Collection
Set FilterCol = this.FilterCol
End Property
Public Property Let FilterCol(ByVal value As Collection)
Set this.FilterCol = value
End Property

Public Property Get N() As Integer
Set N = this.N
End Property
Public Property Let N(ByVal value As Integer)
Set this.N = value
End Property

这个名为“FilterModel”的类是 MSFormObject 的集合。为了正确使用该集合,我需要新建它。所以我使用它的代码看起来有点像这样:

Sub testFilter()
Dim Filterm As FilterModel
Dim DefaultFilterLine As New FilterLine

Set Filterm = New FilterModel
Filterm.FilterCol = New Collection

'Set DefaultFilter
Filterm.FilterCol.Add DefaultFilterLine

'DoStuff
With New frmFilter
Set .Model = Filterm
.Show
End With
End Sub

如果我在添加某些内容之前不新建属性 FilterCol(在本例中为默认过滤器),它将不起作用。这是我的问题:

有没有办法覆盖我的新类的新语句,以便让它也更新到 FilterCol 集合中。据我的研究,我现在知道这将被称为构造函数。

但是如何正确实现 VBA 类的构造函数呢?

类似于:

Private Sub Class_Initialize()
Set this.FilterCol = New Collection
N = 0
End Sub

如果我这样做,那么我会在“Property Let N(Byval Value as integer)”行中收到错误。错误消息显示“需要对象”。

最佳答案

这是一个可行的解决方案。我建议使用 F8 逐行浏览代码以了解那里发生了什么。 Debug.print 将值打印到立即窗口中。

这是FilterModel类:

'''   FilterModel class
Option Explicit

Private pFilterCol As Collection
Private pN As Integer

Public Property Get FilterCol() As Collection
Set FilterCol = pFilterCol
End Property

Public Property Let FilterCol(ByVal value As Collection)
Set pFilterCol = value
End Property

Public Property Get N() As Integer
N = pN
End Property

Public Property Let N(ByVal value As Integer)
pN = value
End Property

Private Sub Class_Initialize()
Set pFilterCol = New Collection
pN = 0
End Sub

这是用于测试它的模块代码:

'''   random module
Option Explicit

Sub testFilter()

Dim Filterm As FilterModel

Set Filterm = New FilterModel
Filterm.FilterCol = New Collection

''' default values (specified in Class_Initialize())
Debug.Print Filterm.N
Debug.Print Filterm.FilterCol.Count

''' set the values through Property Let
Filterm.FilterCol.Add "whatever"
Filterm.FilterCol.Add "whenever"
Filterm.N = 6

''' print the new values (through Property Get)
Debug.Print Filterm.N
Debug.Print Filterm.FilterCol.Count
Debug.Print Filterm.FilterCol(1)
Debug.Print Filterm.FilterCol(2)

End Sub

关于excel - 正确编码构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52721256/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com