2017-05-06 9 views
0

に変換私は、次のVBAコードを使用しています:頻繁に繰り返されるコードは、モジュール

Private Sub btnStatistics_click() 
On Error GoTo Err_Handler 

Dim strPasswd As String 
strPasswd = InputBox("Please Enter Password", "Password Required") 

If strPasswd = Format(Now, "Hh") * 2 Then 
    DoCmd.Close acForm, "frmCustomer", acSaveYes 
    DoCmd.OpenForm "frmStatistics", acNormal, "", "", acEdit, acNormal 
    Exit Sub 
Else 
    MsgBox "Incorrect password!", vbOKOnly, "Password Info" 
End If 

Exit_This_Sub: 
    Exit Sub 
Err_Handler: 
    MsgBox "Error #: " & Err.Number & " " & Err.Description 
    Resume Exit_This_Sub 
End Sub 

私は別のことを行うためにさまざまな形で多くのボタンで、このVBAコードを使用しています。私は部分のstrPasswd = Format(Now, "Hh") * 2をモジュールに移動して、1か所で更新/変更できるようにしたいと思います。

答えて

2

それは、移動したいパスワードの唯一のテストであれば、Booleanを返しFunctionを作成します。

Function PasswordOK(strPwd As String) As Boolean 
    PasswordOK = strPwd = Format(Now, "Hh") * 2 
End Function 

、その後、あなたはとしてそれを使用することができます。

If PasswordOK(strPasswd) Then 
    DoCmd.Close acForm, "frmCustomer", acSaveYes 
    DoCmd.OpenForm "frmStatistics", acNormal, "", "", acEdit, acNormal 
    'Exit Sub '<-- this isn't needed, because the next 
      ' statement after this one is also Exit Sub 
Else 
    MsgBox "Incorrect password!", vbOKOnly, "Password Info" 
End If 

また、適切な場合は、さらにいくつかのパラメータを渡すことで、さらに多くのコードを共通ルーチンに移動できます。

Sub ChangeForm(oldForm As String, newForm As String) 
    Dim strPasswd As String 
    strPasswd = InputBox("Please Enter Password", "Password Required") 

    If strPasswd = Format(Now, "Hh") * 2 Then 
     DoCmd.Close acForm, oldForm, acSaveYes 
     DoCmd.OpenForm newForm, acNormal, "", "", acEdit, acNormal 
    Else 
     MsgBox "Incorrect password!", vbOKOnly, "Password Info" 
    End If 
End Sub 

と共通ルーチンに、単にパスワードの入力、およびそのテストを入れ、

Private Sub btnStatistics_click() 
    ChangeForm "frmCustomer", "frmStatistics" 
End Sub 
おそらくどこかの二つの間

それともとしてそれを使用します。

Function PasswordOK() As Boolean 
    Dim strPasswd As String 
    strPasswd = InputBox("Please Enter Password", "Password Required") 
    If strPasswd = Format(Now, "Hh") * 2 Then 
     PasswordOK = True 
    Else 
     MsgBox "Incorrect password!", vbOKOnly, "Password Info" 
     PasswordOK = False 
    End If 
End Function 

次のように使用してください。

+0

Thあなたをアンク。私は最初のものはOKだと思います。異なるコマンドが毎回実行されるためです。 – YvetteLee

+0

申し訳ありません。私はそれをテストし、それは正常に動作しています。 'Dim strPasswd As String'と' strPasswd = InputBox( "Please Enter Password"、 "Password Required") 'を残さなければならないのですか? – YvetteLee

+0

@YvetteLee最初の方法(関数の中でパスワードのテストのみが行われている)を使用している場合、依然としてメインコードにパスワードを入力する必要があります。私は入力とテストを行うが、残りの部分は実行しない第3のメソッドを追加するように答えを更新します。 – YowE3K

関連する問題