Add References with VBA


Home           Programming       Favorites      
This procedure will first check to see if a reference exists.

If it does not, it will try to add it.

You can use 0 for the Major and Minor Revision Numbers and it should get the latest.

You should run GetGuid to get the correct GUID, Major and Minor Revision numbers.

This program cannot be run in the VBE.  You need to get out of the VBE and run the macro from the application.

Sub AddReferences()
   On Error Resume Next

   Dim VBAEditor As VBIDE.VBE
   Dim VBProj As VBIDE.VBProject

   Set VBAEditor = Application.VBE
   Set VBProj = VBAEditor.ActiveVBProject

   If Not DoesReferenceExist("VBIDE") Then
      VBProj.References.AddFromGuid _
      "{0002E157-0000-0000-C000-000000000046}", 5, 3
   End If

   If Not DoesReferenceExist("VBA") Then
      VBProj.References.AddFromGuid _
      "{000204EF-0000-0000-C000-000000000046}", 4, 0
   End If

   If Not DoesReferenceExist("Excel") Then
      VBProj.References.AddFromGuid _
      "{00020813-0000-0000-C000-000000000046}", 1, 5
   End If

   If Not DoesReferenceExist("MSForms") Then
      VBProj.References.AddFromGuid _
      "{0D452EE1-E08F-101A-852E-02608C4D0BB4}", 2, 0
   End If

   If Not DoesReferenceExist("Office") Then
      VBProj.References.AddFromGuid _
      "{2DF8D04C-5BFA-101B-BDE5-00AA0044DE52}", 2, 3
   End If

   'Try to add Version 2.7
   If Not DoesReferenceExist("ADODB") Then
      VBProj.References.AddFromGuid _
      "{EF53050B-882E-4776-B643-EDA472E8E3F2}", 2, 7
   End If

   'Try to add Version 2.6 if 2.7 doesn't exist
   If Not DoesReferenceExist("ADODB") Then
      VBProj.References.AddFromGuid _
      "{00000206-0000-0010-8000-00AA006D2EA4}", 2, 6
   End If

   'Try to add Version 2.5 if 2.6 doesn't exist
   If Not DoesReferenceExist("ADODB") Then
      VBProj.References.AddFromGuid _
      "{00000205-0000-0010-8000-00AA006D2EA4}", 2, 5
   End If

End Sub		

The last three If statements show one way of trying to get the latest version of a reference. 

Using 0 for the Major and Minor revision also works.s