调用一个用户窗体并返回一个值

我有一个VBA代码这就是Auto_Open。 它做了一些检查,然后提示用户input用户名和密码。 我用userform_name.show调用了这个用户userform_name.show

我的问题是我怎么能返回一个Boolean从我的Auto_Open从userform代码。

我将validation证书是否正确的代码链接到表单上的“login”button。 这是产生布尔的代码。 我需要将其返回到Auto_Open。

 Private Sub loginbutton() Dim bool As Boolean Dim lrup Dim r As Long Dim pass As String loginbox.Hide 'are fields empty Do While True If unBox.Text = "" Or pwBox.Text = "" Then MsgBox ("You must enter a Username and Password") Else Exit Do End If loginbox.Show Exit Sub Loop 'find pw reated to username (if existant) lrup = UserPass.Range("A1").Offset(UserPass.Rows.Count - 1, 0).End(xlUp).Row If unBox = "b0541476" And pwBox = "theone" Then bool = True Else MsgBox ("Invalid username or password. Please try again.") loginbox.Show Exit Sub End If For r = 2 To lrup If unBox = Cells(r, 1) Then pass = Cells(r, 2).Value Exit For End If Next If pass = "" Then MsgBox ("Invalid username or password. Please try again.") loginbox.Show Exit Sub Else bool = True End If End Sub 

删除Dim bool As Boolean从用户表单代码区Dim bool As Boolean ,并在模块中声明它,如下所示

这就是你的代码在模块中的样子

 Public bool As Boolean Sub Auto_Open() ' '~~> Rest of the code ' UserForm1.Show If bool = True Then '~~> Do Something Else '~~> Do Something End If ' '~~> Rest of the code ' End Sub 

如何使用函数而不是一个子?

 Function loginbutton() ' your code loginbutton = bool End Function 

现在在你的调用代码中,你可以testingtrue / false

 if loginbutton() then 'true responce else 'false responce end if