我有一个使用添加新模块功能创建的加载项。这是代码:
Public Function CreateModule(strModulename As String)
Dim strModName As String
10 On Error GoTo err
20 DoCmd.RunCommand acCmdNewObjectModule
30 strModName = "Module1"
40 DoCmd.Save acModule, strModName
50 DoCmd.Rename strModulename, acModule, strModName
60 DoCmd.Save acModule, strModulename
ExitHere:
70 Exit Function
80 err: Call LogError("CreateModule-Utils")
End Function
当我运行时,它给出错误“命令或操作‘NewObjectModule’现在不可用。”。但是,如果我休息一下并逐步执行,它不会出现错误并且可以正常工作,尝试了 sleep 和 DoEvent 但无济于事。任何想法表示赞赏。
type here
尝试使用 VBA Extensibility 库:
Public Sub AddModule(ByVal ModuleName As String)
Dim vbp As VBIDE.VBProject
Dim vbc As VBIDE.VBComponent
Dim currentVbProject As String
currentVbProject = Application.GetOption("Project Name")
Set vbp = Application.VBE.VBProjects(currentVbProject)
Set vbc = vbp.VBComponents.Add(vbext_ct_StdModule)
vbc.Name = ModuleName
' Insert code.
vbc.CodeModule.InsertLines 4, "Public Sub HelloWorld" & vbCrLf & " MsgBox(""Hello, World!"") " & vbCrLf & "End Sub"
' Save module.
DoCmd.Save acModule, ModuleName
Set vbp = Nothing
Set vbc = Nothing
End Sub
所需参考资料:
Microsoft Visual Basic 应用程序扩展性 5.3
原始代码:Philipp Stiefel Codekabinett