Call Excel Add-In function from Excel workbook VSTO

天涯浪子 提交于 2019-12-04 18:07:31

After doing much googleing i m able to answer it myself now.

Please follow the following steps,

  1. Declare an interface with functions you want to expose from your workbook and set its ComVisible attribute to true,

Public Interface ICallMe Sub MyFunction() End Interface

  1. Now create a class which implements this interface and set its ComVisible attribute to true, along with classinterface attribute to None, some what like this,

Public Class AddInUtilities Implements ICallMe

Public Sub MyFunction() Implements ICallMe.MyFunction
    Dim activeWorksheet As Excel.Worksheet = Globals.ThisAddIn.Application.ActiveSheet

    If activeWorksheet IsNot Nothing Then
        Dim range1 As Excel.Range = activeWorksheet.Range("A1")
        range1.Value2 = "This comes from my Add-In"
    End If
End Sub

End Class

  1. 5.Build your add-in project with the Register for COM interop option. To set "Register for Com Interop" option, goto project property and then to "Compile" tab (In VB.net), and set the "Register for COM interop" to check.

  2. Now in your excel workbook project, add the refrence to this add-in and on any event of your workbook like button click, write the following code,

Dim addIn As Office.COMAddIn = Application.COMAddIns.Item("ImportData")

Dim utilities As ImportData.ICallMe = TryCast(addIn.Object, ImportData.ICallMe)

utilities.MyFunction()

You are done :)

Only thing to remeber is that do not call the add-in function from startup event of your workbook or sheet.

I hope it helps you all, as it works for me.

Thanks, Mrinal Jaiswal

Thanks a lot that worked for me. Was struggling with it for 2 days now. I wanted to create a new workbook on the fly in Office 2016 with my Excel Addin, user defined function.

Just a sample how I made it work :

public static void printToExcel(String writeToCell)
{
    Workbook xlWorkbook = Globals.ThisAddIn.Application.Workbooks.Add();
    Worksheet xlWorkSheet = xlWorkbook.ActiveSheet;
    xlWorkSheet.Name = "testSheet";
    xlWorkSheet.Cells[1, 1] = writeToCell;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!