560 attributed reviews in the last 3 years
Refreshingly small course sizes
Outstandingly good courseware
Whizzy online classrooms
Wise Owls only (no freelancers)
Almost no cancellations
We have genuine integrity
We invoice after training
Review 30+ years of Wise Owl
View our top 100 clients
|Creating references programmatically in VBA|
|Did you know that you can create and manage references from within VBA code? This article gives you ideas on how to do just that.|
It is a little-known fact (well, I keep forgetting it!) that you can create and manage your references within VBA.
You need to make sure that you are comfortable with the earlier parts of this blog series on referencing other VBA applications before reading any further.
To work with references from within VBA code, you first need to create a reference (it's all a bit circular!) to the Microsoft Visual Basic for Applications Extensibility library:
Create a reference to the Microsoft VBA Extensibility Library
To do this, select Tools -> References from the VBA code editor menu, and tick the box shown above.
To give you an idea of what's possible, here is a simple program to list out all of the references in the current code project:
'create a variable to refer to each reference
Dim ref As Reference
'list out all of the current references
For Each ref In Application.VBE.ActiveVBProject.References
Debug.Print ref.Name, ref.Description
Here VBE refers to the Visual Basic editor within which you are writing code. The program above might show the following output:
The truncated output from the above program in the immediate window
If you have problems running the code above, you may need to tell your application to trust the VBA project object model (Andrew has blogged in full on macro security too).
A reference object has a fair few properties:
Some of the properties of a reference - the most useful are listed below.
Here are some of the most useful properties:
What it gives
A short description of the reference
A longer description
A unique identifier for the reference
Where the object library is
Whether the reference is broken
You can use the AddFromGUID or AddFromFile methods to add a new reference. For example:
'try to add a reference to Word
On Error GoTo CanNotAddWord
Application.VBE.ActiveVBProject.References.AddFromFile "C:\Program Files\Office 2010\Office14\MSWORD.OLB"
MsgBox "Can not reference Word"
The code above would create a reference to the Word 2010 object library, provided that the relevant object library is in the folder given.
25 Aytoun Street