我正在开发一个用户应用程序,与您现在面临的问题相同,here is the answer I got there.
请检查上面的链接,因为 Mat's Mugs 的解释超出了我解释该主题的能力。但这里有一个缩写。
基本上你做的是以下。您有三个类:模型、视图和演示者类。这听起来超级复杂,但一旦你掌握了它,它就真的没那么难了。
模型
是一个存储所有数据的类模块。因此,您不必声明一堆公共变量,而是拥有一个存储所有数据的大类。您还可以将多个模型类和类作为类成员,但为简单起见,我们仅采用上述三个整数。
这里是一个model 类的例子:(把它全部放在一个名为model 的类模块中)
Option Explicit
' encapsulated data
Private Type TModel
a As Integer
b As Integer
c As Integer
End Type
Private this As TModel
' property get and property let define the way you can interact with data
Public Property Get a() As String
a = this.a
End Property
Public Property Let a(ByVal value As String)
this.a = value
End Property
Public Property Get b() As String
b = this.b
End Property
Public Property Let b(ByVal value As String)
this.b = value
End Property
Public Property Get c() As String
c = this.c
End Property
Public Property Let c(ByVal value As String)
this.c = value
End Property
观点
这是您的用户表单。但是您的 UserForm 又是一个类,所以除了所有其他代码之外,您还有以下代码:
Private Type TView
M As Model
IsCancelled As Boolean
IsBack As Boolean
End Type
Private this As TView
Public Property Get Model() As Model
Set Model = this.M
End Property
Public Property Set Model(ByVal value As UImodel)
Set this.M= value
'Validate
End Property
' This is responsible for not destroying all data you have when you x-out the userform
Public Property Get IsCancelled() As Boolean
IsCancelled = this.IsCancelled
End Property
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = VbQueryClose.vbFormControlMenu Then
this.IsCancelled=True
Cancel = True
OnCancel
End If
End Sub
Private Sub OKButton_Click()
Model.a = TextBox1.value
Model.b = TextBox2.value
Model.c = TextBox3.value
Cells(1, 1).value = Model.a
Cells(2, 1).value = Model.b
Cells(3, 1).value = Model.c
'this displays the inputs properly
Me.Hide
End Sub
演示者
这是一个普通的模块。您简单地将代码放在您使用这些东西的地方。因此,对于您的示例代码,如下所示:
Public Sub Login()
'in module
Dim Ufrm As New UserForm1
Dim M As New Model
Set Ufrm.Model = M
Ufrm.Show
If Ufrm.IsCancelled Then Exit Sub
Set M = Ufrm.Model
MsgBox M.a
MsgBox M.b
MsgBox M.c
End Sub