You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在MS Access中使用全局变量时出现运行时错误的求助

解决Access VBA登录表单全局变量赋值的2467错误

错误原因

触发Run-time error '2467'的核心问题是代码执行顺序错误:你先调用DoCmd.Close关闭了当前登录表单,之后再尝试访问Me.txtUsername——此时表单已被关闭,对应的控件对象不存在,自然会抛出“引用的对象已关闭或不存在”的错误。

修复方案

调整代码顺序,先把用户名赋值给全局变量,再关闭登录表单:

If Nz(DLookup("Password", "Users", "Login = '" & Me.txtUsername.Value & "'"), "GarbageEntry") = Me.txtPassword Then
    ' 先完成全局变量赋值,再关闭表单
    gstrActiveUser = Me.txtUsername.Value
    DoCmd.Close
    DoCmd.OpenForm "Equipment Lookup"
    MsgBox gstrActiveUser
Else
    ' 可添加登录失败提示逻辑
    MsgBox "用户名或密码错误"
End If

额外优化建议(针对Access新手)

  • 直接拼接SQL语句存在SQL注入风险,如果用户名包含单引号(如O'Neil),代码会直接报错。建议改用参数化查询验证密码:
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT Password FROM Users WHERE Login = ?", dbOpenDynaset, dbSeeChanges)
rs.Parameters(0) = Me.txtUsername.Value

If Not rs.EOF Then
    If Nz(rs!Password, "GarbageEntry") = Me.txtPassword Then
        gstrActiveUser = Me.txtUsername.Value
        DoCmd.Close
        DoCmd.OpenForm "Equipment Lookup"
        MsgBox gstrActiveUser
    Else
        MsgBox "密码错误"
    End If
Else
    MsgBox "用户名不存在"
End If
rs.Close
Set rs = Nothing
Set db = Nothing
  • Access全局变量可能因编译错误、意外重启等情况丢失值,更可靠的存储方式是使用TempVars集合:
    ' 赋值
    TempVars("ActiveUser") = Me.txtUsername.Value
    ' 在其他表单中获取值
    Dim currentUser As String
    currentUser = TempVars("ActiveUser").Value
    

内容的提问来源于stack exchange,提问作者Tom W

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 13:52:42