首页 文章

在VBA中将变量从Form传递给Module

提问于
浏览
19

我在表单上有以下按钮:

Private Sub CommandButton1_Click()
 Dim pass As String
 pass = UserForm1.TextBox1
 Unload UserForm1
End Sub

然后我有一个名为Module1的模块:

Public Sub Login()

 ...

 UserForm1.Show
 driver.findElementByName("PASSWORD").SendKeys pass

 ...

End Sub

这个想法是用户输入到输入框的任何密码都将被分配给变量 pass . 然而,我遇到的麻烦是将 pass 从UserForm1传递给Module1的Login子 .

我想在卸载它之前在我的表单中添加类似 Module1.Login (pass) 的东西会起作用,但是这似乎没有通过任何东西 . 任何帮助将非常感激 . 谢谢 .

2 回答

  • 29

    不要在userform中声明变量 . 在模块中将其声明为 Public .

    Public pass As String
    

    In the Userform

    Private Sub CommandButton1_Click()
        pass = UserForm1.TextBox1
        Unload UserForm1
    End Sub
    

    In the Module

    Public pass As String
    
    Public Sub Login()
        '
        '~~> Rest of the code
        '
        UserForm1.Show
        driver.findElementByName("PASSWORD").SendKeys pass
        '
        '~~> Rest of the code
        '
    End Sub
    

    您可能还想在调用 driver.find... 行之前添加额外的检查?

    If Len(Trim(pass)) <> 0 Then
    

    这将确保不传递空字符串 .

  • 15

    Siddharth的答案很好,但依赖于全局范围的变量 . 有一种更好,更友好的OOP方式 .

    UserForm是一个类模块,与其他任何类似 - 唯一的区别是它有一个隐藏的 VB_PredeclaredId 属性设置为 True ,这使得VB创建一个以类命名的全局范围对象变量 - 这就是如何在不创建新的情况下编写 UserForm1.Show 类的实例 .

    远离这个,并将您的表单视为对象 - 公开 Property Get 成员并抽象出形式's controls - the calling code doesn' t关心控件:

    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
            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
    

相关问题