excel 中的后期绑定 VBIDE.VBE

Late Binding VBIDE.VBE in excel

是否可以在 Excel 中延迟绑定 VBIDE.VBE 对象?例如:

Dim VBAEditor As VBIDE.VBE

而是变成类似这样的东西(后期绑定):

Dim VBAEditor As Object: set VBAEditor = CreateObject ("VBIDE.VBE")

我的目标是避免手动进入 select "Microsoft Visual Basic for Applications Extensibility 5.3" 参考的复选框。

解决方案

使用下面的反馈,我能够以编程方式动态添加 "Microsoft Visual Basic for Applications Extensibility 5.3" 引用。解决方法如下:

Sub mainFunction()

    Call AddLib("VBIDE", "{0002E157-0000-0000-C000-000000000046}", 5, 3)

    ' Bunch of working code goes here

End Sub

'******************************************************************************
'AddLib: Adds a library reference to this script programmatically, so that
'        libraries do not need to be added manually.
'******************************************************************************
Private Function AddLib(libName As String, guid As String, major As Long, minor As Long)

    Dim exObj As Object: Set exObj = GetObject(, "Excel.Application")
    Dim vbProj As Object: Set vbProj = exObj.ActiveWorkbook.VBProject
    Dim chkRef As Object

    ' Check if the library has already been added
    For Each chkRef In vbProj.References
        If chkRef.Name = libName Then
            GoTo CleanUp
        End If
    Next

    vbProj.References.AddFromGuid guid, major, minor

CleanUp:
    Set vbProj = Nothing
End Function

我深受 this stack article on dynamic referencing in excel.

启发

是的,根据 Excel forms: identify unused code 您可以使用后期绑定

Dim VBProj
Dim VBComp
Set VBProj = ActiveWorkbook.VBProject
For Each VBComp In VBProj.vbcomponents

等等