您需要首先枚举项目的引用,以检查引用是否已经存在。
我添加了对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