如何以编程方式添加引用

Omm*_*mit 83 excel vba reference

我已经编写了一个程序来运行,并在完成后向Skype发送信息.我需要添加一个参考Skype4COM.dll,以便通过Skype发送消息.我们在网络上有十几台计算机和一个共享文件服务器(除其他外).所有其他计算机都需要能够运行此程序.我希望避免手动设置参考.我曾计划将引用放在共享位置,并在程序运行时以编程方式添加引用.

我似乎无法弄清楚如何使用VBA以编程方式将引用添加到Excel 2007.我知道如何手动完成:打开VBE --> Tools --> References --> browse --_> File Location and Name.但这对我的目的来说并不是很有用.我知道有一些方法可以在Access Vb.net中执行此操作,并且类似于此的代码不断弹出,但我不确定我是否理解它,或者它是否相关:

ThisWorkbook.VBProject.References.AddFromGuid _
    GUID:="{0002E157-0000-0000-C000-000000000046}", _
    Major:=5, Minor:=3
Run Code Online (Sandbox Code Playgroud)

到目前为止,在所提出的解决方案中,为了以编程方式添加引用,我需要手动添加引用并更改信任中心 - 这不仅仅是添加引用.虽然我想如果我按照提出的解决方案进行操作,我将能够以编程方式添加未来的参考.这可能值得付出努力.

任何进一步的想法都会很棒.

Sid*_*out 102

Ommit

有两种方法可以通过VBA向项目添加引用

1)使用GUID

2)直接引用dll.

让我报道两者.

但首先,这些是你需要照顾的3件事

a)应启用宏

b)在安全设置中,确保选中"信任对Visual Basic项目的访问"

在此输入图像描述

c)您已手动设置对"Microsoft Visual Basic for Applications Extensibility"对象的引用

在此输入图像描述

方式1(使用GUID)

我通常避免这种方式,因为我必须在注册表中搜索GUID ...我讨厌LOL.更多关于GUID的信息.

主题:通过代码添加VBA参考库

链接:http://www.vbaexpress.com/kb/getarticle.php?kb_id = 267

'Credits: Ken Puls
Sub AddReference()
     'Macro purpose:  To add a reference to the project using the GUID for the
     'reference library

    Dim strGUID As String, theRef As Variant, i As Long

     'Update the GUID you need below.
    strGUID = "{00020905-0000-0000-C000-000000000046}"

     'Set to continue in case of error
    On Error Resume Next

     'Remove any missing references
    For i = ThisWorkbook.VBProject.References.Count To 1 Step -1
        Set theRef = ThisWorkbook.VBProject.References.Item(i)
        If theRef.isbroken = True Then
            ThisWorkbook.VBProject.References.Remove theRef
        End If
    Next i

     'Clear any errors so that error trapping for GUID additions can be evaluated
    Err.Clear

     'Add the reference
    ThisWorkbook.VBProject.References.AddFromGuid _
    GUID:=strGUID, Major:=1, Minor:=0

     'If an error was encountered, inform the user
    Select Case Err.Number
    Case Is = 32813
         'Reference already in use.  No action necessary
    Case Is = vbNullString
         'Reference added without issue
    Case Else
         'An unknown error was encountered, so alert the user
        MsgBox "A problem was encountered trying to" & vbNewLine _
        & "add or remove a reference in this file" & vbNewLine & "Please check the " _
        & "references in your VBA project!", vbCritical + vbOKOnly, "Error!"
    End Select
    On Error GoTo 0
End Sub
Run Code Online (Sandbox Code Playgroud)

方式2(直接引用dll)

此代码添加了对引用的引用 Microsoft VBScript Regular Expressions 5.5

Option Explicit

Sub AddReference()
    Dim VBAEditor As VBIDE.VBE
    Dim vbProj As VBIDE.VBProject
    Dim chkRef As VBIDE.Reference
    Dim BoolExists As Boolean

    Set VBAEditor = Application.VBE
    Set vbProj = ActiveWorkbook.VBProject

    '~~> Check if "Microsoft VBScript Regular Expressions 5.5" is already added
    For Each chkRef In vbProj.References
        If chkRef.Name = "VBScript_RegExp_55" Then
            BoolExists = True
            GoTo CleanUp
        End If
    Next

    vbProj.References.AddFromFile "C:\WINDOWS\system32\vbscript.dll\3"

CleanUp:
    If BoolExists = True Then
        MsgBox "Reference already exists"
    Else
        MsgBox "Reference Added Successfully"
    End If

    Set vbProj = Nothing
    Set VBAEditor = Nothing
End Sub
Run Code Online (Sandbox Code Playgroud)

注意:我没有添加错误处理.建议在实际代码中使用它:)

编辑被打败mischab1:)

  • 对于记录,MS Scripting Runtime的GUID是"{420B2830-E718-11CF-893D-00A0C9054228}".您可以手动添加其他GUID,然后循环遍历每个`Ref`` ThisWorkbook.VBProject.References`并使用`Debug.Print Ref.Name,Ref.Guid` (9认同)
  • 所以似乎不是手动添加引用而是需要手动添加单独的引用并更改excel权限?虽然它将来会更好,但现在看起来有点好笑. (2认同)
  • 是的,听起来确实很有趣,但此刻就是这样:) (2认同)
  • 在不同版本的Windows中,某些DLL的文件夹位置是否会有所不同?(例如Win 8,Win 7,Vista,XP等).在这种情况下,不会通过GUID添加更安全(如果您的用户在不同的Win版本)? (2认同)

mis*_*ab1 24

有两种方法可以使用VBA添加引用..AddFromGuid(Guid, Major, Minor).AddFromFile(Filename).哪一个最好取决于您尝试添加引用的内容.我几乎总是使用,.AddFromFile因为我引用的东西是其他Excel VBA项目,它们不在Windows注册表中.

您显示的示例代码将添加对代码所在工作簿的引用.我通常没有看到任何意义,因为90%的时间,在您添加引用之前,代码已经无法编译因为缺少参考.(如果它没有编译失败,你可能正在使用后期绑定,你不需要添加引用.)

如果您在运行代码时遇到问题,则可能存在两个问题.

  1. 为了轻松使用VBE的对象模型,您需要添加对Microsoft Visual Basic for Application Extensibility的引用.(VBIDE)
  2. 要运行更改VBProject中任何内容的Excel VBA代码,您需要信任对VBA项目对象模型的访问权限.(在Excel 2010中,它位于信任中心 - 宏设置中.)

除此之外,如果您可以更清楚地了解您的问题是什么或者您尝试做什么不起作用,我可以给出更具体的答案.


hen*_*nep 8

浏览注册表以获取guid或使用路径,哪种方法最好.如果不再需要浏览注册表,那么使用guid是不是更好的方法?Office并不总是安装在同一目录中.可以手动更改安装路径.版本号也是路径的一部分.我从来没有预料到微软会在引入64位处理器之前将'(x86)'添加到'Program Files'.如果可能的话,我会尽量避免使用路径.

下面的代码源自Siddharth Rout的答案,附加功能列出了活动工作簿中使用的所有引用.如果我在更高版本的Excel中打开我的工作簿怎么办?如果不修改VBA代码,工作簿是否仍然有效?我已经检查过办公室2003年和2010年的指南是相同的.让我们希望微软在未来的版本中不会改变guid.

参数0,0(来自.AddFromGuid)应该使用最新版本的引用(我无法测试).

你的想法是什么?当然,我们无法预测未来,但我们可以做些什么来使我们的代码版本证明?

Sub AddReferences(wbk As Workbook)
    ' Run DebugPrintExistingRefs in the immediate pane, to show guids of existing references
    AddRef wbk, "{00025E01-0000-0000-C000-000000000046}", "DAO"
    AddRef wbk, "{00020905-0000-0000-C000-000000000046}", "Word"
    AddRef wbk, "{91493440-5A91-11CF-8700-00AA0060263B}", "PowerPoint"
End Sub

Sub AddRef(wbk As Workbook, sGuid As String, sRefName As String)
    Dim i As Integer
    On Error GoTo EH
    With wbk.VBProject.References
        For i = 1 To .Count
            If .Item(i).Name = sRefName Then
               Exit For
            End If
        Next i
        If i > .Count Then
           .AddFromGuid sGuid, 0, 0 ' 0,0 should pick the latest version installed on the computer
        End If
    End With
EX: Exit Sub
EH: MsgBox "Error in 'AddRef'" & vbCrLf & vbCrLf & err.Description
    Resume EX
    Resume ' debug code
End Sub

Public Sub DebugPrintExistingRefs()
    Dim i As Integer
    With Application.ThisWorkbook.VBProject.References
        For i = 1 To .Count
            Debug.Print "    AddRef wbk, """ & .Item(i).GUID & """, """ & .Item(i).Name & """"
        Next i
    End With
End Sub
Run Code Online (Sandbox Code Playgroud)

上面的代码不再需要引用"Microsoft Visual Basic for Applications Extensibility"对象.

  • 请注意,您必须启用宏并选中“对Visual Basic项目的信任访问”(@Siddharth_Rout中[answer](/sf/answers/691619351/中的点a和b)),但对于+1消除VBIDE参考!另外,我感谢DebugPrintExistingRefs以将其复制并粘贴到代码中的格式输出它。 (3认同)

Cha*_*owe 5

这是如何以编程方式获取Guid的方法!然后,您可以将这些guid / filepaths与上面的答案一起使用来添加参考!

参考:http : //www.vbaexpress.com/kb/getarticle.php? kb_id= 278

Sub ListReferencePaths()
'Lists path and GUID (Globally Unique Identifier) for each referenced library.
'Select a reference in Tools > References, then run this code to get GUID etc.
    Dim rw As Long, ref
    With ThisWorkbook.Sheets(1)
        .Cells.Clear
        rw = 1
        .Range("A" & rw & ":D" & rw) = Array("Reference","Version","GUID","Path")
        For Each ref In ThisWorkbook.VBProject.References
            rw = rw + 1
            .Range("A" & rw & ":D" & rw) = Array(ref.Description, _
                   "v." & ref.Major & "." & ref.Minor, ref.GUID, ref.FullPath)
        Next ref
        .Range("A:D").Columns.AutoFit
    End With
End Sub
Run Code Online (Sandbox Code Playgroud)

这是相同的代码,但是如果您不想将工作表专用于输出,则打印到终端。

Sub ListReferencePaths() 
 'Macro purpose:  To determine full path and Globally Unique Identifier (GUID)
 'to each referenced library.  Select the reference in the Tools\References
 'window, then run this code to get the information on the reference's library

On Error Resume Next 
Dim i As Long 

Debug.Print "Reference name" & " | " & "Full path to reference" & " | " & "Reference GUID" 

For i = 1 To ThisWorkbook.VBProject.References.Count 
  With ThisWorkbook.VBProject.References(i) 
    Debug.Print .Name & " | " & .FullPath  & " | " & .GUID 
  End With 
Next i 
On Error GoTo 0 
End Sub 
Run Code Online (Sandbox Code Playgroud)