我用VBA access做了一个数据库。我想在欢迎表上显示登录名。请指导我在这方面。我试图通过公共变量将用户名从登录表单传递到欢迎表单,但没有工作。我的代码如下:-登录表单代码
enter code here
Public strUserID As String
Private Sub cmdLogin_Click()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim strSQL As String
If IsNull(Me.txtLoginID) Or Me.txtLoginID = "" Then
MsgBox "Enter user Name.....", vbInformation, "Whiz Alert!"
Me.txtLoginID.SetFocus
Exit Sub
End If
If IsNull(Me.txtPassword) Or Me.txtPassword = "" Then
MsgBox "Enter Password.....", vbInformation, "Whiz Alert!"
Me.txtPassword.SetFocus
Exit Sub
End If
strSQL = "SELECT UserID FROM User WHERE LoginID = """ & Me.txtLoginID.Value & """ AND Password = """ & Me.txtPassword.Value & """"
Set db = CurrentDb
Set rst = db.OpenRecordset(strSQL)
If rst.EOF Then
MsgBox "Incorrect Username/Password.", vbCritical, "Login Error"
Me.txtLoginID.SetFocus
Else
DoCmd.Close acForm, "Index", acSaveYes
DoCmd.OpenForm "HomePage", acNormal, , , , acWindowNormal
DoCmd.Close acForm, "UserLoginForm", acSaveYes
End If
Set db = Nothing
Set rst = Nothing
End Sub
Private Sub txtLoginID_AfterUpdate()
strUserID = Me.txtLoginID
End Sub
欢迎表格代码
Private Sub Form_Current()
Me.txtUser = UserLoginForm.strUserID
End Sub
我会把登录操作移到一个单独的函数中,并根据返回值来操作。
一个简单的登录方法,返回 True
如果登录成功,或 False
如果不是的话。这里不需要打开一个记录集,一个简单的 DCount()
就可以了。
Public Function TryToLogin(ByVal Username As Variant, ByVal Password As Variant) As Boolean
On Error GoTo Trap
'validation
Select Case True
Case IsNull(Username):
MsgBox "Enter user Name.....", vbInformation, "Whiz Alert!"
GoTo Leave
Case IsNull(Password):
MsgBox "Enter Password.....", vbInformation, "Whiz Alert!"
GoTo Leave
End Select
'credentials correct?
If DCount("UserID", "User", "LoginID='" & Username & "' AND Password='" & Password & "'") = 0 Then
MsgBox "Incorrect Username/Password.", vbExclamation, "Login Error"
GoTo Leave
End If
'login successful
TryToLogin = True
Leave:
On Error GoTo 0
Exit Function
Trap:
MsgBox Err.Description, vbCritical
Resume Leave
End Function
方法(我假设是按钮点击事件)来调用登录函数。检查返回值并根据它采取行动。如果成功,您可以使用表单的 OpenArgs
参数。我推测欢迎形式是首页?
Private Sub Button_Click()
If Not TryToLogin(txtLoginID.Value, txtPassword.Value) Then Exit Sub
With DoCmd
.Close acForm, "Index", acSaveYes
.OpenForm "HomePage", acNormal, , , , acWindowNormal, txtLoginID.Value
.Close acForm, "UserLoginForm", acSaveYes
End With
End Sub
最后,处理好 OpenArgs
在欢迎表格的 Load()
事件。
Private Sub Form_Load()
If Not IsNull(OpenArgs) Then
'the OpenArgs now holds the username.
End If
End Sub