【发布时间】:2017-07-04 10:14:33
【问题描述】:
我创建了一个 VBA 用户窗体,它本质上是一个美化的输入框
就像输入框可以这样使用
Dim returnVal As String
returnVal = InputBox("Write some string")
我希望我的用户表单像这样运行
Dim returnVal As customClass
Set returnVal = MyUserForm([some arguments])
即。 MyUserForm() 代码将一些参数传递给用户窗体,当用户窗体关闭时,它会返回一些参数(以自定义类的形式而不是纯字符串的形式)
构建用户表单以实现此功能的最佳方式是什么?
目前,我只是公开声明一些变量和自定义类。我正在捕捉命令按钮点击和Query_close() 事件来隐藏表单,然后我读取了 outputVal 并完全关闭了表单。我不喜欢这样,因为我希望我的表单完全独立,而且我认为事件的捕获很混乱。
在简化代码中(读取/返回字符串):
Function myUf(inVal As String) As String
Dim frm As New frmTest
frm.inputval = inVal
frm.Init 'sets caption. We cannot rely on userform initialize as this runs before inputval is set
'We could pass a variable here to save writing to the public variable
frm.Show
myUf = frm.outputVal
Set frm = Nothing
End Function
在我名为frmTest 的用户表单中,带有一个名为tb1 的文本框
Public inputval As String
Public outputVal As String
Public Sub Init()
Me.Caption = inputval 'setting caption, but could pass this anywhere
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode <> 1 Then Cancel = 1
outputVal = tb1 'reading value from textbox, but could return anything here
Me.Hide
End Sub
【问题讨论】: