8

Auto_Open の vba コードがあります。いくつかのチェックを行い、ユーザー名とパスワードを要求するユーザーフォームを表示します。このユーザーフォームを で呼び出しましたuserform_name.show

私の問題は、ユーザーフォームコードからサブに aBooleanを返す方法です。Auto_Open

資格情報が正しいかどうかを検証するコードをフォームの「ログイン」ボタンにリンクしました。これはブール値を生成するコードです。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
4

4 に答える 4

4

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
于 2013-09-23T18:34:03.663 に答える
2

サブの代わりに関数を使用するのはどうですか?

Function loginbutton()
  ' your code

  loginbutton = bool
End Function

これで、呼び出しコードで true/false をテストできます

if loginbutton() then
  'true responce
else
  'false responce
end if
于 2013-09-23T18:37:01.723 に答える