【问题标题】:Run-time error 7961 when referring to Modules(name) for Form modules引用表单模块的模块(名称)时出现运行时错误 7961
【发布时间】:2016-04-20 21:58:22
【问题描述】:

Modules() 集合包含所有打开的模块,包括位于表单后面的模块。但我不知道如何引用表单后面的模块。在下面的代码中(来自即时窗格),命名约定是以“M_”开头的对象是独立模块,而以“F_”开头的对象是表单。

从即时窗格中:

'Proving that the method works for standalone modules:
debug.print Modules("M_Test").Name
M_Test

' Proving I am spelling the name of the form correctly:
debug.Print currentproject.AllForms("F_Inserts").Name
F_Inserts

' Proving the form is open (so it appears in Modules() collection)
debug.Print currentproject.AllForms("F_Inserts").IsLoaded
True

很好。尝试访问表单后面的模块 - 不要忘记,所有表单的模块都以“Form_”为前缀:

debug.Print Modules("Form_F_Inserts").Name
debug.Print Modules("F_Inserts").Name

两次都导致运行时错误 7961 -“找不到宏表达式或 Visual Basic 代码中引用的模块 'Form_F_Inserts'”。 现在几乎和往常一样,“帮助”按钮坏了,把我带到“无法服务请求”错误页面 (https://msdn.microsoft.com/Areas/Epx/Content/500.aspx?aspxerrorpath=/query/dev11.query)。

该例程的目的是为每个表单模块获取.CountOfLines。以下是全部内容:

Dim lOut As String, lVariant As Variant, lInt As Integer, lBool As Boolean
lInt=0
For Each lVariant In CurrentProject.AllForms
    lBool = lVariant.IsLoaded   'If not loaded, we open it & close it after
    If Not lBool Then DoCmd.OpenForm lVariant.Name, acDesign, WindowMode:=acHidden
    If Forms(lVariant.Name).HasModule Then lInt = lInt + Modules("Form_" & lVariant.Name).CountOfLines
    If Not lBool Then DoCmd.Close acForm, lVariant.Name, acSaveNo
Next

有什么想法吗?

【问题讨论】:

    标签: ms-access vba ms-access-2013


    【解决方案1】:

    Modules() 集合包含所有打开的模块,包括 位于表单后面的模块。

    因此,假设您的 F_Inserts 表单已打开,您可以引用其 Module 属性并从那里获取 CountOfLines

    'Debug.Print Modules("Form_F_Inserts").Name     ' fail
    'Debug.Print Modules("F_Inserts").Name          ' fail
    Debug.Print Forms!F_Inserts.Module.Name         '<-- this should return "Form_F_Inserts"
    Debug.Print Forms!F_Inserts.Module.CountOfLines '<-- this should work, too
    

    但是,如果您想检索未打开的模块的 CountOfLines,请使用带有表单模块名称的 VBE 对象模型 (Form_F_Inserts)...

    With Application.VBE.ActiveVBProject
        Debug.Print .VBComponents("Form_F_Inserts").CodeModule.CountOfLines
    End With
    

    如果每个表单模块都需要CountOfLines,也许这就足够了……

    Dim objComponent As Object ' VBComponent
    Dim strName As String
    
    For Each objComponent In Application.VBE.ActiveVBProject.VBComponents
        strName = objComponent.Name
        If strName Like "Form_*" Then
            Debug.Print strName, objComponent.CodeModule.CountOfLines
        End If
    Next
    

    【讨论】:

      猜你喜欢
      • 2016-05-31
      • 2017-04-16
      • 2015-02-27
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 2022-07-19
      • 1970-01-01
      • 2019-06-26
      相关资源
      最近更新 更多