开发者

Call Excel Add-In function from Excel workbook VSTO

开发者 https://www.devze.com 2022-12-17 11:46 出处:网络
I want to create a Method in Excel Add-In 2007 solution which can be called from my Excel Workbook 2007 solution.

I want to create a Method in Excel Add-In 2007 solution which can be called from my Excel Workbook 2007 solution.

I explain, I want to call a me开发者_StackOverflowthod of Excel Add-In from code behind file of excel workbook 2007 solution. And I dont want to use VBA Macros.

Please help, thanks in advance

Thanks, Mrinal Jaiswal


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号