运行-引用Form模块的Modules(name)时报错7961

Run-time error 7961 when referring to Modules(name) for Form modules

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

导致 运行-time error 7961 两次 - "can't find the module 'Form_F_Inserts' referred to in a macro expression or Visual Basic code"。 现在几乎一如既往,"Help" 按钮坏了,将我带到 "Unable to Service Request" 错误页面 (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

有什么想法吗?

The Modules() collection contains all open modules, including the modules that sit behind forms.

因此假设您的 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