VB6 & .accdb 数据库登录表单



我想知道是否有人可以帮助我解决这个问题。我有一个登录表单,其中包含一个名为 cboUsername 的组合框,以及一个名为 txtPassword 的密码文本框。我有访问数据库的"雇员"表的表单,并用.accdb中"strEmpName"字段中的"雇员姓名"填充组合框,并且我遇到问题,并且我无法根据字段名称为strEmpPassword的同一表检查密码。我正在尝试做的是,如果密码匹配,则允许访问该软件。除此之外,我还有一个名为strAccess的字段,允许用户访问软件的某些部分。strAccess 可以是"管理员"、"用户"或"只读"。谁能帮我解决问题?我的工作代码如下:

Option Explicit
Private Sub Form_Load()
Dim db_file As String
Dim statement As String
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
cboUsername.Text = "Select Username"
' Get the data.
db_file = App.Path
If Right$(db_file, 1) <> "" Then db_file = db_file & ""
db_file = db_file & "FluidFlo.accdb"
' Open a connection.
Set conn = New ADODB.Connection
conn.ConnectionString = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & db_file & ";" & "Persist Security Info=False"
conn.Open
' Select the data.
statement = "SELECT strEmpName FROM tblEmployees ORDER BY strEmpName"
' Get the records.
Set rs = conn.Execute(statement, , adCmdText)
' Load the results into the ComboBox
Do Until rs.EOF
cboUsername.AddItem rs!strEmpName
rs.MoveNext
Loop
' Close the recordset and connection.
rs.Close
conn.Close
End Sub

我希望我已经明确了我想要完成的目标,并一如既往地提前感谢大家!

我有一个产生 Windows 用户名的函数

Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Public Function LoginName() As Variant
Dim ret As Long
Dim s As String * 255
Dim pos As Long
ret = GetUserName(s, 255)
pos = InStr(s, vbNullChar)
If pos <= 1 Then
LoginName = Null
Else
LoginName = Left$(s, pos - 1)
End If
End Function

使用此功能,您只需询问密码,而无需使用用户名填充组合框。

使用此其他函数

Public Function SqlStr(ByVal s As String) As String
'Input: s=""      Returns: NULL
'Input: s="abc"   Returns: 'abc'
'Input: s="x'y"   Returns: 'x''y'
If s = "" Then
SqlStr = "NULL"
Else
SqlStr = "'" & Replace(s, "'", "''") & "'"
End If
End Function

您可以通过以下方式检查密码

If DCount("*", "tblEmployees", _
"strEmpName = " & SqlStr(LoginName()) & " AND strPwd = " & SqlStr(txtPassword)) = 1 Then
...
Else
...
End If

顺便说一句,如果此代码位于包含表的 accdb 中或这些表链接到的 accdb 中,则无需创建连接并使用 ADODB。只需将此查询SELECT strEmpName FROM tblEmployees ORDER BY strEmpName放在 ComboBox 的Row Source属性中即可。

备注:这是访问VBA代码。


更新

从您新发布的代码中,我看到您正在将员工 ID 与员工姓名 ([lngEmpID]=" & Me.cboUsername.Value( 进行比较,这当然不起作用。

确保组合框的Row Source TypeTable/Query。将此代码放在组合框的Row Source属性中。

SELECT lngEmpID, strEmpName FROM tblEmployees ORDER BY strEmpName

与您的代码相比,这将添加 Id。 将Column Count设置为2Column Widths设置为0cm。这将隐藏组合框中的 Id 列。现在,组合框的值是 Id 而不是名称。

最新更新