Add reference programmatically

Sanjay Kulkarni 0 Reputation points

I have searched the net for almost 4 hours using a variety of phrases but could get a simple workable solution.
So here is my problem:
How to add references to a VB Project programmatically.

In VBA, I can use Application.VBE.ActiveVBProject.References.AddByFile ...
What is equivalent code in VB.Net

An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,077 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Castorix31 71,606 Reputation points

    It can be done with System.Reflection

    Test with Excel 2016 Interop (just open Excel, show 1 second, quit) :

        Dim sExcel = "Microsoft.Office.Interop.Excel, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
        Dim assembly = System.Reflection.Assembly.Load(sExcel)
        Dim oExcel = assembly.CreateInstance("Microsoft.Office.Interop.Excel.ApplicationClass")
        ' Test
        Dim methods As MethodInfo() = oExcel.[GetType]().GetMethods(BindingFlags.[Public] Or BindingFlags.Instance)
        Dim props As PropertyInfo() = oExcel.[GetType]().GetProperties()
        ' {Void set_Visible(Boolean)}
        ' {Void Quit()}
        InvokeMethod(oExcel, "set_Visible", True)
        InvokeMethod(oExcel, "Quit", Nothing)

    with :

        ' https//       
        Public Shared Function InvokeMethod(ByVal obj As Object, ByVal methodName As String, ParamArray methodParams As Object()) As Object
            Dim methodParamTypes = If(methodParams?.[Select](Function(p) p.GetType()).ToArray(), New Type() {})
            Dim bindingFlags = Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Static
            Dim method As MethodInfo = Nothing
            Dim type = obj.GetType()
            While method Is Nothing AndAlso type IsNot Nothing
                method = type.GetMethod(methodName, bindingFlags, Type.DefaultBinder, methodParamTypes, Nothing)
                type = type.BaseType
            End While
            Return method?.Invoke(obj, methodParams)
        End Function