0% found this document useful (0 votes)
121 views8 pages

How To Add A Reference Programmatically Vba-Excel - Stack Overflow

Uploaded by

Tri Nguyen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
121 views8 pages

How To Add A Reference Programmatically Vba-Excel - Stack Overflow

Uploaded by

Tri Nguyen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Ngày 5 tháng 2 năm 2015 How to add a reference programmatically vba-Excel - Stack Overflow

sign up log in tour help stack overflow careers

Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no
Take the 2-minute tour ×
registration required.

How to add a reference programmatically vba-Excel

I can't seem to figure out how to add a reference programmatically to Excel 2007 using vba. I know how to do it manually Open VBE -->
Tools --> References --> browse --_> File Location and Name. But that's not very useful for my purposes.

I know there are ways to do it in Access [Link] and code similar to this kept popping up, but I'm not sure I understand it, or if it's relevant.

[Link] _
GUID:="{0002E157-0000-0000-C000-000000000046}", _
Major:=5, Minor:=3

Edit: Thanks for your quick [Link]'ve helped quite a bit but so far no solution will be viable for my problem. (which is clearly my
fault for not giving enough details). Here's exactly what I'm trying to do.

I've written a program that runs and messages skype with information when if finishes. I need to add a reference for [Link] in order
to send a message through Skype. We have a dozen or so computers on a network and a shared file server (among other things). All of the
other computers need to be able to run this program. I was hoping to avoid setting up the reference by hand. I had planned on putting the
reference in a shared location, and adding it programmatically when the program ran. And that's where I got stumped and asked my original
question.

So far, in the solutions presented, in order to add the reference programmatically I will need to add a reference by hand and change the
trust centre...which is more than just adding the reference.

Though I guess if I follow through with the solutions proposed I will be able to add future references programmatically. Which probably
makes it worth the effort.

Any further thought would be great.

excel vba excel-vba reference

edited Jan 9 '14 at 20:53 asked Mar 26 '12 at 21:02


Siddharth Rout Ommit
66.8k 8 63 82 308 2 5 18

you can use CreateObject() without adding reference under Excel 2010 – Qbik Dec 19 '14 at 15:44

3 Answers

Ommit

There are two ways to add references via VBA to your projects

1) Using GUID

2) Directly referencing the dll.

Let me cover both.

But first these are 3 things you need to take care of

a) Macros should be enabled

b) In Security settings, ensure that "Trust Access To Visual Basic Project" is checked

[Link] 1/8
Ngày 5 tháng 2 năm 2015 How to add a reference programmatically vba-Excel - Stack Overflow

c) You have manually set a reference to `Microsoft Visual Basic for Applications Extensibility"
object

Way 1 (Using GUID)

I usually avoid this way as I have to search for the GUID in the registry... which I hate LOL. More
on GUID here.

Topic: Add a VBA Reference Library via code

Link: [Link]

Way 2 (Directly referencing the dll)

This code adds a reference to Microsoft VBScript Regular Expressions 5.5

Option Explicit

Sub AddReference()
Dim VBAEditor As [Link]
Dim vbProj As [Link]
Dim chkRef As [Link]
Dim BoolExists As Boolean

Set VBAEditor = [Link]


Set vbProj = [Link]

'~~> Check if "Microsoft VBScript Regular Expressions 5.5" is already added


For Each chkRef In [Link]
If [Link] = "VBScript_RegExp_55" Then
BoolExists = True
GoTo CleanUp
End If
Next

[Link] "C:\WINDOWS\system32\[Link]\3"

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

[Link] 2/8
Ngày 5 tháng 2 năm 2015 How to add a reference programmatically vba-Excel - Stack Overflow
End If

Set vbProj = Nothing


Set VBAEditor = Nothing
End Sub

Note : I have not added Error Handling. It is recommended that in your actual code, do use it :)

EDIT Beaten by mischab1 :)

edited Sep 28 '14 at 16:53 answered Mar 26 '12 at 21:41


Community ♦ Siddharth Rout
1 66.8k 8 63 82

3 +1 for awesome detail. Great response. – Ommit Mar 27 '12 at 15:19

So it seems that instead of adding the reference by hand I need to add a separate reference by hand and
change excel permissions? Granted it will be better in the future, but it seems a little funny now. – Ommit
Mar 27 '12 at 20:09

Yes it does sound funny but then that's how it is at the moment :) – Siddharth Rout Mar 27 '12 at 20:25

Great answer. FYI users of this, notice that you still can't use any Word/PowerPoint/other object or Enum
outside of a function or procedure with this since the compiler will fail before the WORKBOOK_OPEN event
begins executing. So you can't create a Public Word object and you can't define the type of a parameter as
a Word/PPT type (eg you can't do something like Sub CopyActiveChartToWord(FormatType as
WdPasteDataType)). – s_a Apr 7 '14 at 16:28

Won't the folder locations of some DLL's be different in different versions of Windows? (eg Win 8, Win 7,
Vista, XP, etc). In which case, won't adding by GUID be safer (if your users are on different Win versions)? –
johny why Jul 6 '14 at 21:17

There are two ways to add references using VBA. .AddFromGuid(Guid, Major, Minor) and
.AddFromFile(Filename). Which one is best depends on what you are trying to add a reference
to. I almost always use .AddFromFile because the things I am referencing are other Excel VBA
Projects and they aren't in the Windows Registry.

The example code you are showing will add a reference to the workbook the code is in. I generally
don't see any point in doing that because 90% of the time, before you can add the reference, the
code has already failed to compile because the reference is missing. (And if it didn't fail-to-
compile, you are probably using late binding and you don't need to add a reference.)

If you are having problems getting the code to run, there are two possible issues.

1. In order to easily use the VBE's object model, you need to add a reference to Microsoft
Visual Basic for Application Extensibility . (VBIDE)
2. In order to run Excel VBA code that changes anything in a VBProject, you need to Trust
access to the VBA Project Object Model. (In Excel 2010, it is located in the Trust Center -
Macro Settings.)

Aside from that, if you can be a little more clear on what your question is or what you are trying to
do that isn't working, I could give a more specific answer.

answered Mar 26 '12 at 21:39


mischab1
1,028 5 10

+1 for posting it before me ;) – Siddharth Rout Mar 26 '12 at 21:42

[Link] 3/8
Ngày 5 tháng 2 năm 2015 How to add a reference programmatically vba-Excel - Stack Overflow

This is the code I have used in [Link]

Dim oXL As [Link]


Dim oWB As [Link]
Dim oSheet As [Link]
Dim oRng As [Link]

' Start Excel and get Application object.


oXL = CreateObject("[Link]")
[Link] = True

' Get a new workbook.


oWB = [Link]
oSheet = [Link]

The class below outputs an Excel spreadsheet based on the contents of 2 data tables. It's [Link]
but I believe that the OLE Automation is the same for VBA.

You need to include references

[Link], Microsoft Excel 14.0 Object Library

This code is 8 years old so sorry there is so much of it but it includes some useful fixes and
workarounds to make a proper job.

'Option Strict Off to allow automation of MS Office components


Option Strict Off
Imports [Link]
Imports [Link]

Public Class ResultXls

'///////////
' Variables
'///////////

Private Const _ReportName = "Result"

Enum WorksheetRows
EventTitle = 1
RaceTitle
RaceDate
ResultsHeader
ResultsData
End Enum

'Pos, Boat No, Boat Name, Driver, Navigator, Laps, Time, NMiles, Miles, Km,
Knots, Mph, Kmph, Points
Enum BoatHeadings
Pos
BoatNo
BoatName
Driver
Navigator
Laps
Time
NMiles
Miles
Km
Knots
Mph
Kmph
Points
End Enum

'Class variables
Private _RaceDb As RaceDb

Public Sub New(ByVal RaceDB As RaceDb)


_RaceDb = RaceDB
End Sub

'///////////////////
' Public Procedures
'///////////////////

Public Sub CreateExcelWorksheet(ByVal RaceId As Integer)

Dim oXL As [Link]


Dim oWB As [Link]
Dim oSheet As [Link]
Dim oRng As [Link]

'Load datatables
Dim RaceDataTable As DataTable = _RaceDb.GetRaceInfoDataTable(RaceId)

[Link] 4/8
Ngày 5 tháng 2 năm 2015 How to add a reference programmatically vba-Excel - Stack Overflow
Dim RaceResultDataTable As DataTable =
_RaceDb.GetRaceResultsDataTable(RaceId)

' Start Excel and get Application object.


oXL = CreateObject("[Link]")
[Link] = True

' Get a new workbook.


oWB = [Link]
oSheet = [Link]

'************
' Page Setup
'************

'[Link] = [Link]([Link](0)
("RaceDate")).ToString("yyyy-MM-dd") + " - " + [Link](0)
("RaceName").ToString() + " - " + [Link](0)("RaceClass").ToString()

[Link] = [Link]
[Link] = 1
[Link] = 1
[Link] = True

'******************
' Results Headings
'******************

'Pos, Boat No, Boat Name, Driver, Navigator, Laps, Time, NMiles, Miles, Km,
Knots, Mph, Kmph, Points

'Set headings
[Link]([Link], [Link] + 1).Value = "Pos"
[Link]([Link], [Link] + 1).Value =
"Number"
[Link]([Link], [Link] + 1).Value =
"Boat"
[Link]([Link], [Link] + 1).Value =
"Driver"
[Link]([Link], [Link] + 1).Value =
"Navigator"
[Link]([Link], [Link] + 1).Value =
"Laps"
[Link]([Link], [Link] + 1).Value =
"Time"
[Link]([Link], [Link] + 1).Value =
"NMiles"
[Link]([Link], [Link] + 1).Value =
"Miles"
[Link]([Link], [Link] + 1).Value = "Km"
[Link]([Link], [Link] + 1).Value =
"Knots"
[Link]([Link], [Link] + 1).Value = "Mph"
[Link]([Link], [Link] + 1).Value =
"Kmh"
[Link]([Link], [Link] + 1).Value =
"Points"

'Format headings
Dim headingRange As [Link] = [Link]("A" +
[Link]([Link]), "N" +
[Link]([Link]))
[Link] = "Arial"
[Link] = 10
[Link] = True
[Link] = [Link]
[Link] = [Link]
[Link] = [Link]

'**************
' Results Data
'**************

'Pos, Boat No, Boat Name, Driver, Navigator, Laps, Time, NMiles, Miles, Km,
Knots, Mph, Kmph, Points

'Load boat data


Dim boat As Integer
Dim datarow As DataRow
For boat = 0 To [Link] - 1

'[Link] '"Position", "Pos"


'[Link] '"BoatNumberText", "Number"
'[Link] '"BoatName", "Boat"
'[Link] '"Driver", "Driver"
'[Link] '"Navigator", "Navigator"
'[Link] '"TotalLapsCompleted", "Laps"
'[Link] '"RaceElapsedTimeHHMMSS", "Time"
'[Link] '"CompletedNm", "NMiles"
'[Link] '"CompletedMiles", "Miles"

[Link] 5/8
Ngày 5 tháng 2 năm 2015 How to add a reference programmatically vba-Excel - Stack Overflow
'[Link] '"CompletedKm", "Km"
'[Link] '"RaceSpeedKnots", "Knots"
'[Link] '"RaceSpeedMph", "Mph"
'[Link] '"RaceSpeedKmh", "Kmh"
'[Link] '"Points", "Points"

datarow = [Link](boat)

[Link]([Link] + boat, [Link] +


1).Value = datarow("Position")
[Link]([Link] + boat, [Link] +
1).Value = datarow("BoatNumberText")
[Link]([Link] + boat, [Link] +
1).Value = datarow("BoatName")
[Link]([Link] + boat, [Link] +
1).Value = datarow("Driver")
[Link]([Link] + boat, [Link] +
1).Value = datarow("Navigator")
[Link]([Link] + boat, [Link] +
1).Value = datarow("TotalLapsCompleted")
[Link]([Link] + boat, [Link] +
1).Value = datarow("RaceElapsedTimeHHMMSS")
[Link]([Link] + boat, [Link] +
1).Value = datarow("CompletedNm")
[Link]([Link] + boat, [Link] +
1).Value = datarow("CompletedMiles")
[Link]([Link] + boat, [Link] + 1).Value
= datarow("CompletedKm")
[Link]([Link] + boat, [Link] +
1).Value = datarow("RaceSpeedKnots")
[Link]([Link] + boat, [Link] +
1).Value = datarow("RaceSpeedMph")
[Link]([Link] + boat, [Link] +
1).Value = datarow("RaceSpeedKmh")
[Link]([Link] + boat, [Link] +
1).Value = datarow("Points")

Next

'Format columns
Dim range As [Link]
'Time
range = [Link]("G" + [Link]([Link]), "G" +
[Link]([Link]([Link] +
[Link] - 1)))
[Link] = "hh:mm:ss.00"
'NMiles
range = [Link]("H" + [Link]([Link]), "H" +
[Link]([Link]([Link] +
[Link] - 1)))
[Link] = "0.00"
'Miles
range = [Link]("I" + [Link]([Link]), "I" +
[Link]([Link]([Link] +
[Link] - 1)))
[Link] = "0.00"
'Km
range = [Link]("J" + [Link]([Link]), "J" +
[Link]([Link]([Link] +
[Link] - 1)))
[Link] = "0.00"
'Knots
range = [Link]("K" + [Link]([Link]), "J" +
[Link]([Link]([Link] +
[Link] - 1)))
[Link] = "0.00"
'Mph
range = [Link]("L" + [Link]([Link]), "L" +
[Link]([Link]([Link] +
[Link] - 1)))
[Link] = "0.00"
'Kmph
range = [Link]("M" + [Link]([Link]), "M" +
[Link]([Link]([Link] +
[Link] - 1)))
[Link] = "0.00"

'Format results data


Dim resultsRange As [Link] = [Link]("A" +
[Link]([Link]), "N" +
[Link]([Link]([Link] +
[Link] - 1)))
[Link] = [Link]
[Link] = [Link]
[Link]()

'Points
range = [Link]("N" + [Link]([Link]), "N" +
[Link]([Link]([Link] +
[Link] - 1)))

[Link] 6/8
Ngày 5 tháng 2 năm 2015 How to add a reference programmatically vba-Excel - Stack Overflow
[Link] = [Link]
[Link] = [Link]

'********
' Titles
'********

'Add titles last so that AutoFit format is not affected

'RaceId, RaceYear, RaceNumber, RaceName, RaceDate, RaceClass, LapNMiles,


LapMiles, LapKm, RaceLaps, RaceStartDateTime, RaceEndDateTime

'EventTitle
[Link]([Link], 1).Value =
[Link]([Link](0)("EventTitle"))
Dim racenameRange As [Link] = [Link]("A" +
[Link]([Link]), "N" +
[Link]([Link]))
[Link] = "Arial"
[Link] = 12
[Link] = True
[Link]()
[Link] = [Link]

'RaceTitle
[Link]([Link], 1).Value =
[Link]([Link](0)("RaceTitle"))
Dim classnameRange As [Link] = [Link]("A" +
[Link]([Link]), "N" +
[Link]([Link]))
[Link] = "Arial"
[Link] = 12
[Link] = True
[Link]()
[Link] = [Link]

'Date
[Link]([Link], 1).Value = "'" +
[Link]([Link](0)("RaceDate")).ToString("dd MMM yyyy ddd")
Dim racedateRange As [Link] = [Link]("A" +
[Link]([Link]), "A" +
[Link]([Link]))
[Link] = "Arial"
[Link] = 12
[Link] = True
[Link] = [Link]

'Laps
Dim totalLaps As Integer = NullInt([Link](0)("StartLaps")) +
NullInt([Link](0)("RaceLaps")) + NullInt([Link](0)
("PitLaps"))
[Link]([Link], 14).Value = [Link](totalLaps)
+ " Laps"
Dim racelapsRange As [Link] = [Link]("N" +
[Link]([Link]), "N" +
[Link]([Link]))
[Link] = "Arial"
[Link] = 12
[Link] = True
[Link] = [Link]

'**********
' Clean Up
'**********

'Make Excel visible and give the user control of Excel's lifetime
[Link] = True
[Link] = True

'Save
Dim dateText As String = [Link]([Link](0)
("RaceDate")).ToString("yyyy-MM-dd")
Dim dayText As String = Left([Link]([Link](0)
("RaceDate")).[Link](), 3)
Dim eventText As String = [Link](0)("EventTitle").ToString()
Dim raceText As String = [Link](0)("RaceTitle").ToString()
Dim filename = [Link]("{0} {1} {2} {3} {4}", dateText, dayText,
eventText, raceText, _ReportName)
Try
[Link](filename:=filename)
Catch ex As Exception
[Link]("Failed to save report", "Save Error",
[Link], [Link], MessageBoxDefaultButton.Button1)
End Try

'Release object references


oRng = Nothing
oSheet = Nothing
oWB = Nothing
'[Link]()

[Link] 7/8
Ngày 5 tháng 2 năm 2015 How to add a reference programmatically vba-Excel - Stack Overflow
oXL = Nothing
[Link]()

End Sub

End Class

answered Mar 26 '12 at 21:27


Mark Gittoes
101 3

4 how does this answer the question?! – vba4all Jul 9 '13 at 14:33

[Link] 8/8

You might also like