我正在尝试使用子例程从用户窗体输入中调用变量。 但是,即使我可以通过将用户窗体输入打印到工作表上来正确显示用户窗体输入,但似乎无法将其作为公共变量传递给子例程。当我在子例程中调用变量时,它们都是空的。
我以此为指导: Passing variable from Form to Module in VBA
这是我的代码:
Public a As String
Public b As Double
Public c As String
Private Sub OKButton_Click()
'from userform
a = TextBox1.Value
b = TextBox2.Value
c = TextBox3.Value
Cells(1, 1).Value = a
Cells(2, 1).Value = b
Cells(3, 1).Value = c
'this displays the inputs properly
Unload UserForm1
End Sub
在模块中:
Public Sub Login()
'in module
UserForm1.Show
MsgBox (a)
MsgBox (b)
MsgBox (c)
End Sub
答案 0 :(得分:1)
这样做。将您的公共变量放入模块代码中。
Public a As String
Public b As Double
Public c As String
Public Sub Login()
'in module
UserForm1.Show
MsgBox (a)
MsgBox (b)
MsgBox (c)
End Sub
答案 1 :(得分:0)
我正在开发一个用户应用程序,该应用程序与您现在遇到的问题相同,here is the answer I got there.
请检查上面的链接,因为Mat的杯子的解释超出了我的解释范围。但这是一个缩写。
基本上,您要做的是以下内容。您有三个类:模型,视图和演示者类。这听起来超级复杂,但是一旦掌握了它,实际上并没有那么困难。
模型
是一个用于存储所有数据的类模块。因此,您无需声明一堆公共变量,而是拥有一个存储所有数据的大类。您还可以将多个模型类和多个类作为类成员,但是为简单起见,我们仅采用上述三个整数。
以下是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