How To Add A Reference Programmatically Vba-Excel - Stack Overflow
How To Add A Reference Programmatically Vba-Excel - Stack Overflow
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.
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 Vb.net and code similar to this kept popping up, but I'm not sure I understand it, or if it's relevant.
ThisWorkbook.VBProject.References.AddFromGuid _
GUID:="{0002E157-0000-0000-C000-000000000046}", _
Major:=5, Minor:=3
Edit: Thanks for your quick responses.They'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 Skype4COM.dll 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.
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
b) In Security settings, ensure that "Trust Access To Visual Basic Project" is checked
http://stackoverflow.com/questions/9879825/how-to-add-a-reference-programmatically-vba-excel 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
I usually avoid this way as I have to search for the GUID in the registry... which I hate LOL. More
on GUID here.
Link: http://www.vbaexpress.com/kb/getarticle.php?kb_id=267
Option Explicit
Sub AddReference()
Dim VBAEditor As VBIDE.VBE
Dim vbProj As VBIDE.VBProject
Dim chkRef As VBIDE.Reference
Dim BoolExists As Boolean
vbProj.References.AddFromFile "C:\WINDOWS\system32\vbscript.dll\3"
CleanUp:
If BoolExists = True Then
MsgBox "Reference already exists"
Else
MsgBox "Reference Added Successfully"
http://stackoverflow.com/questions/9879825/how-to-add-a-reference-programmatically-vba-excel 2/8
Ngày 5 tháng 2 năm 2015 How to add a reference programmatically vba-Excel - Stack Overflow
End If
Note : I have not added Error Handling. It is recommended that in your actual code, do use it :)
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.
http://stackoverflow.com/questions/9879825/how-to-add-a-reference-programmatically-vba-excel 3/8
Ngày 5 tháng 2 năm 2015 How to add a reference programmatically vba-Excel - Stack Overflow
The class below outputs an Excel spreadsheet based on the contents of 2 data tables. It's VB.Net
but I believe that the OLE Automation is the same for VBA.
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.
'///////////
' Variables
'///////////
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 Procedures
'///////////////////
'Load datatables
Dim RaceDataTable As DataTable = _RaceDb.GetRaceInfoDataTable(RaceId)
http://stackoverflow.com/questions/9879825/how-to-add-a-reference-programmatically-vba-excel 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)
'************
' Page Setup
'************
'oSheet.Name = Convert.ToDateTime(RaceDataTable.Rows(0)
("RaceDate")).ToString("yyyy-MM-dd") + " - " + RaceDataTable.Rows(0)
("RaceName").ToString() + " - " + RaceDataTable.Rows(0)("RaceClass").ToString()
oSheet.PageSetup.Orientation = Excel.XlPageOrientation.xlLandscape
oSheet.PageSetup.FitToPagesWide = 1
oSheet.PageSetup.FitToPagesTall = 1
oSheet.PageSetup.CenterHorizontally = True
'******************
' Results Headings
'******************
'Pos, Boat No, Boat Name, Driver, Navigator, Laps, Time, NMiles, Miles, Km,
Knots, Mph, Kmph, Points
'Set headings
oSheet.Cells(WorksheetRows.ResultsHeader, BoatHeadings.Pos + 1).Value = "Pos"
oSheet.Cells(WorksheetRows.ResultsHeader, BoatHeadings.BoatNo + 1).Value =
"Number"
oSheet.Cells(WorksheetRows.ResultsHeader, BoatHeadings.BoatName + 1).Value =
"Boat"
oSheet.Cells(WorksheetRows.ResultsHeader, BoatHeadings.Driver + 1).Value =
"Driver"
oSheet.Cells(WorksheetRows.ResultsHeader, BoatHeadings.Navigator + 1).Value =
"Navigator"
oSheet.Cells(WorksheetRows.ResultsHeader, BoatHeadings.Laps + 1).Value =
"Laps"
oSheet.Cells(WorksheetRows.ResultsHeader, BoatHeadings.Time + 1).Value =
"Time"
oSheet.Cells(WorksheetRows.ResultsHeader, BoatHeadings.NMiles + 1).Value =
"NMiles"
oSheet.Cells(WorksheetRows.ResultsHeader, BoatHeadings.Miles + 1).Value =
"Miles"
oSheet.Cells(WorksheetRows.ResultsHeader, BoatHeadings.Km + 1).Value = "Km"
oSheet.Cells(WorksheetRows.ResultsHeader, BoatHeadings.Knots + 1).Value =
"Knots"
oSheet.Cells(WorksheetRows.ResultsHeader, BoatHeadings.Mph + 1).Value = "Mph"
oSheet.Cells(WorksheetRows.ResultsHeader, BoatHeadings.Kmph + 1).Value =
"Kmh"
oSheet.Cells(WorksheetRows.ResultsHeader, BoatHeadings.Points + 1).Value =
"Points"
'Format headings
Dim headingRange As Excel.Range = oSheet.Range("A" +
Convert.ToString(WorksheetRows.ResultsHeader), "N" +
Convert.ToString(WorksheetRows.ResultsHeader))
headingRange.Font.Name = "Arial"
headingRange.Font.Size = 10
headingRange.Font.Bold = True
headingRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
headingRange.Borders.LineStyle = Excel.XlLineStyle.xlContinuous
headingRange.Borders.Weight = Excel.XlBorderWeight.xlThin
'**************
' Results Data
'**************
'Pos, Boat No, Boat Name, Driver, Navigator, Laps, Time, NMiles, Miles, Km,
Knots, Mph, Kmph, Points
http://stackoverflow.com/questions/9879825/how-to-add-a-reference-programmatically-vba-excel 5/8
Ngày 5 tháng 2 năm 2015 How to add a reference programmatically vba-Excel - Stack Overflow
'BoatHeadings.Km '"CompletedKm", "Km"
'BoatHeadings.Knots '"RaceSpeedKnots", "Knots"
'BoatHeadings.Mph '"RaceSpeedMph", "Mph"
'BoatHeadings.Kmph '"RaceSpeedKmh", "Kmh"
'BoatHeadings.Points '"Points", "Points"
datarow = RaceResultDataTable.Rows(boat)
Next
'Format columns
Dim range As Excel.Range
'Time
range = oSheet.Range("G" + Convert.ToString(WorksheetRows.ResultsData), "G" +
Convert.ToString(Convert.ToString(WorksheetRows.ResultsData +
RaceResultDataTable.Rows.Count - 1)))
range.NumberFormat = "hh:mm:ss.00"
'NMiles
range = oSheet.Range("H" + Convert.ToString(WorksheetRows.ResultsData), "H" +
Convert.ToString(Convert.ToString(WorksheetRows.ResultsData +
RaceResultDataTable.Rows.Count - 1)))
range.NumberFormat = "0.00"
'Miles
range = oSheet.Range("I" + Convert.ToString(WorksheetRows.ResultsData), "I" +
Convert.ToString(Convert.ToString(WorksheetRows.ResultsData +
RaceResultDataTable.Rows.Count - 1)))
range.NumberFormat = "0.00"
'Km
range = oSheet.Range("J" + Convert.ToString(WorksheetRows.ResultsData), "J" +
Convert.ToString(Convert.ToString(WorksheetRows.ResultsData +
RaceResultDataTable.Rows.Count - 1)))
range.NumberFormat = "0.00"
'Knots
range = oSheet.Range("K" + Convert.ToString(WorksheetRows.ResultsData), "J" +
Convert.ToString(Convert.ToString(WorksheetRows.ResultsData +
RaceResultDataTable.Rows.Count - 1)))
range.NumberFormat = "0.00"
'Mph
range = oSheet.Range("L" + Convert.ToString(WorksheetRows.ResultsData), "L" +
Convert.ToString(Convert.ToString(WorksheetRows.ResultsData +
RaceResultDataTable.Rows.Count - 1)))
range.NumberFormat = "0.00"
'Kmph
range = oSheet.Range("M" + Convert.ToString(WorksheetRows.ResultsData), "M" +
Convert.ToString(Convert.ToString(WorksheetRows.ResultsData +
RaceResultDataTable.Rows.Count - 1)))
range.NumberFormat = "0.00"
'Points
range = oSheet.Range("N" + Convert.ToString(WorksheetRows.ResultsData), "N" +
Convert.ToString(Convert.ToString(WorksheetRows.ResultsData +
RaceResultDataTable.Rows.Count - 1)))
http://stackoverflow.com/questions/9879825/how-to-add-a-reference-programmatically-vba-excel 6/8
Ngày 5 tháng 2 năm 2015 How to add a reference programmatically vba-Excel - Stack Overflow
range.Borders.LineStyle = Excel.XlLineStyle.xlContinuous
range.Borders.Weight = Excel.XlBorderWeight.xlThin
'********
' Titles
'********
'EventTitle
oSheet.Cells(WorksheetRows.EventTitle, 1).Value =
Convert.ToString(RaceDataTable.Rows(0)("EventTitle"))
Dim racenameRange As Excel.Range = oSheet.Range("A" +
Convert.ToString(WorksheetRows.EventTitle), "N" +
Convert.ToString(WorksheetRows.EventTitle))
racenameRange.Font.Name = "Arial"
racenameRange.Font.Size = 12
racenameRange.Font.Bold = True
racenameRange.Merge()
racenameRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
'RaceTitle
oSheet.Cells(WorksheetRows.RaceTitle, 1).Value =
Convert.ToString(RaceDataTable.Rows(0)("RaceTitle"))
Dim classnameRange As Excel.Range = oSheet.Range("A" +
Convert.ToString(WorksheetRows.RaceTitle), "N" +
Convert.ToString(WorksheetRows.RaceTitle))
classnameRange.Font.Name = "Arial"
classnameRange.Font.Size = 12
classnameRange.Font.Bold = True
classnameRange.Merge()
classnameRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
'Date
oSheet.Cells(WorksheetRows.RaceDate, 1).Value = "'" +
Convert.ToDateTime(RaceDataTable.Rows(0)("RaceDate")).ToString("dd MMM yyyy ddd")
Dim racedateRange As Excel.Range = oSheet.Range("A" +
Convert.ToString(WorksheetRows.RaceDate), "A" +
Convert.ToString(WorksheetRows.RaceDate))
racedateRange.Font.Name = "Arial"
racedateRange.Font.Size = 12
racedateRange.Font.Bold = True
racedateRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft
'Laps
Dim totalLaps As Integer = NullInt(RaceDataTable.Rows(0)("StartLaps")) +
NullInt(RaceDataTable.Rows(0)("RaceLaps")) + NullInt(RaceDataTable.Rows(0)
("PitLaps"))
oSheet.Cells(WorksheetRows.RaceDate, 14).Value = Convert.ToString(totalLaps)
+ " Laps"
Dim racelapsRange As Excel.Range = oSheet.Range("N" +
Convert.ToString(WorksheetRows.RaceDate), "N" +
Convert.ToString(WorksheetRows.RaceDate))
racelapsRange.Font.Name = "Arial"
racelapsRange.Font.Size = 12
racelapsRange.Font.Bold = True
racelapsRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignRight
'**********
' Clean Up
'**********
'Make Excel visible and give the user control of Excel's lifetime
oXL.Visible = True
oXL.UserControl = True
'Save
Dim dateText As String = Convert.ToDateTime(RaceDataTable.Rows(0)
("RaceDate")).ToString("yyyy-MM-dd")
Dim dayText As String = Left(Convert.ToDateTime(RaceDataTable.Rows(0)
("RaceDate")).DayOfWeek.ToString(), 3)
Dim eventText As String = RaceDataTable.Rows(0)("EventTitle").ToString()
Dim raceText As String = RaceDataTable.Rows(0)("RaceTitle").ToString()
Dim filename = String.Format("{0} {1} {2} {3} {4}", dateText, dayText,
eventText, raceText, _ReportName)
Try
oWB.SaveAs(filename:=filename)
Catch ex As Exception
MessageBox.Show("Failed to save report", "Save Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
End Try
http://stackoverflow.com/questions/9879825/how-to-add-a-reference-programmatically-vba-excel 7/8
Ngày 5 tháng 2 năm 2015 How to add a reference programmatically vba-Excel - Stack Overflow
oXL = Nothing
GC.Collect()
End Sub
End Class
4 how does this answer the question?! – vba4all Jul 9 '13 at 14:33
http://stackoverflow.com/questions/9879825/how-to-add-a-reference-programmatically-vba-excel 8/8