gpt4 book ai didi

VBA - 自动检查/取消检查微软脚本运行时

转载 作者:行者123 更新时间:2023-12-02 16:39:02 25 4
gpt4 key购买 nike

我有以下功能,可以自动将 Microsoft Script Runtime 引用添加到引用列表中。但是,如果用户已经包含了Microsoft脚本运行时,则会显示错误名称与现有模块、项目、对象库冲突

如何设置一个条件,以便在引用中未包含 Microsoft 脚本运行时 时自动添加它,而在已添加时则不执行任何操作?

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

最佳答案

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

我添加了对 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 引用的早期绑定(bind)引用:

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

但是,如果您对后期绑定(bind)代码的缺点感到满意,您甚至不需要对 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

关于VBA - 自动检查/取消检查微软脚本运行时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47525176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com