我使用以下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
移动到一个模块中,以便我可以在一个地方更新/更改它。
答案 0 :(得分:2)
如果仅测试您要移动的密码,请创建一个返回Function
的{{1}}:
Boolean
然后您可以将其用作:
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