Siddharth的答案不错,但依赖全局作用域变量。有更好、更面向对象友好的方法。
UserForm是一个类模块,和其他任何类一样——唯一的区别在于它具有隐藏的VB_PredeclaredId属性设置为True,这使得VB创建一个名为该类的全局范围对象变量——这就是你可以编写UserForm1.Show
而不创建该类新实例的方式。
远离这个做法,把你的表单当作一个对象处理——公开Property Get
成员并将表单控件抽象化——调用代码无论如何都不关心控件:
Option Explicit
Private cancelling As Boolean
Public Property Get UserId() As String
UserId = txtUserId.Text
End Property
Public Property Get Password() As String
Password = txtPassword.Text
End Property
Public Property Get IsCancelled() As Boolean
IsCancelled = cancelling
End Property
Private Sub OkButton_Click()
Me.Hide
End Sub
Private Sub CancelButton_Click()
cancelling = True
Me.Hide
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = VbQueryClose.vbFormControlMenu Then
cancelling = True
Cancel = True
Me.Hide
End If
End Sub
现在,调用代码可以这样做(假设UserForm被命名为 LoginPrompt
):
With New LoginPrompt
.Show vbModal
If .IsCancelled Then Exit Sub
DoSomething .UserId, .Password
End With
其中DoSomething
将是需求这两个字符串参数的某个过程:
Private Sub DoSomething(ByVal uid As String, ByVal pwd As String)
'work with the parameter values, regardless of where they came from
End Sub
MsgBox pass
但是什么也没有弹出,UserForm 输入的值没有传递到模块! - KiDo