programing

VBA에서 폼에서 모듈로의 변수 전달

showcode 2023. 4. 20. 23:25
반응형

VBA에서 폼에서 모듈로의 변수 전달

양식에 다음 버튼이 있습니다.

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하지만 내가 하는 데 어려움을 겪고 있는 것은 합격이다.passUserForm1에서 Module1의 Login 서브로 이동합니다.

이런 걸 더하는 게 어떨까?Module1.Login (pass)하지만 아무것도 통과되지 않는 것 같습니다.어떤 도움이라도 주시면 감사하겠습니다.감사해요.

사용자 양식에 변수를 선언하지 마십시오.라고 선언하다Public를 참조해 주세요.

Public pass As String

사용자 양식

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

모듈 내

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

이렇게 하면 빈 문자열이 전달되지 않습니다.

Siddharth의 답변은 좋지만 글로벌 범위의 변수에 의존합니다.더 좋고, 더 사용하기 쉬운 방법이 있습니다.

UserForm은 다른 것과 마찬가지로 클래스 모듈입니다.단, 다른 점은 숨김이 있다는 것입니다.VB_PredeclaredId속성 설정TrueVB가 클래스의 이름을 딴 글로벌스코프 객체 변수를 작성하도록 합니다.이렇게 하면, 기입할 수 있습니다.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

이것으로, 발신 코드가 이것을 실행할 수 있게 되었습니다(User Form이 명명된 것을 전제로 합니다).LoginPrompt):

With New LoginPrompt
    .Show vbModal
    If .IsCancelled Then Exit Sub
    DoSomething .UserId, .Password
End With

어디에DoSomething다음 2개의 문자열 파라미터가 필요한 절차입니다.

Private Sub DoSomething(ByVal uid As String, ByVal pwd As String)
    'work with the parameter values, regardless of where they came from
End Sub

언급URL : https://stackoverflow.com/questions/20214072/passing-variable-from-form-to-module-in-vba

반응형