3

我有以下功能自动将Microsoft Script Runtime参考添加到参考列表中。但是,如果用户已经包含Microsoft script runtime了,则会显示错误Name conflicts with existing module,project, object library

Microsoft script runtime如果引用中未包含自动添加的条件,如果已添加,如何设置不执行任何操作?

Private Function AddScriptingLibrary() As Boolean

Const GUID As String = "{420B2830-E718-11CF-893D-00A0C9054228}"

On Error GoTo errHandler
ThisWorkbook.VBProject.References.AddFromGuid GUID, 1, 0
AddScriptingLibrary = True
Exit Function
errHandler:
MsgBox Err.Description

End Function
4

1 回答 1

4

您需要首先枚举项目的引用,以检查引用是否已经存在。

我添加了对Microsoft Visual Basic for Applications Extensibility 5.3的引用

Option Explicit

Function AddScriptingLibrary()

    Const GUID_Scripting = "{420B2830-E718-11CF-893D-00A0C9054228}"

    Dim proj As VBIDE.VBProject
    Dim ref As VBIDE.Reference
    Dim ScriptingLibraryIsReferenced As Boolean

    Set proj = ThisWorkbook.VBProject

    For Each ref In proj.References
      If ref.GUID = GUID_Scripting Then
          ScriptingLibraryIsReferenced = True
          AddScriptingLibrary = True
          Exit Function
      End If
    Next ref

    If Not ScriptingLibraryIsReferenced Then
        On Error GoTo errHandler
        proj.References.AddFromGuid GUID_Scripting, 1, 0
        AddScriptingLibrary = True
        Exit Function

errHandler:
    MsgBox Err.Description
      End If

End Function

编辑此操作相同,但没有对 Visual Basic For Applications Extensibility 5.3 参考的早期绑定参考:

Option Explicit

Function AddScriptingLibrary()

    Const GUID_Scripting = "{420B2830-E718-11CF-893D-00A0C9054228}"

    Dim proj As Object 'VBIDE.VBProject
    Dim ref As Object 'VBIDE.Reference
    Dim ScriptingLibraryIsReferenced As Boolean

    Set proj = ThisWorkbook.VBProject

    For Each ref In proj.References
      If ref.GUID = GUID_Scripting Then
          ScriptingLibraryIsReferenced = True
          AddScriptingLibrary = True
          Exit Function
      End If
    Next ref

    If Not ScriptingLibraryIsReferenced Then
        On Error GoTo errHandler
        proj.References.AddFromGuid GUID_Scripting, 1, 0
        AddScriptingLibrary = True
        Exit Function

errHandler:
    MsgBox Err.Description
      End If

End Function

但是,如果您对后期绑定代码的缺点感到满意,您甚至不需要对 的引用Scripting.Runtime,因为您可以使用:

Option Explicit

Sub PrintDriveCount()

    Dim FSO As Object
    Set FSO = CreateObject("Scripting.FileSystemObject")

    'Print the number of drives in the FileSystemObject
    Debug.Print FSO.Drives.Count

End Function
于 2017-11-28T06:46:47.310 回答