Add user defined function to Visual Studio Excel Add-in

后端 未结 4 2127
长发绾君心
长发绾君心 2021-01-04 08:45

In visual studio I have an Excel 2010 Add-in project. How can I have that project create the following module:

\

4条回答
  •  再見小時候
    2021-01-04 09:01

    I dont think that VSTO supports Excel UDF's, the general recommendation is to use Automation Add-in's (as Sid's link suggests).

    Another option is to call a managed VSTO function from VBA. Once again this is not recommended but possible.

    (Recap of tutorial from link) Here is any easy way to call Managed functions from VBA.

    Create a class with your functions in VSTO

     _
    Public Class MyManagedFunctions
        Public Function GetNumber() As Integer
            Return 42
        End Function
    End Class
    

    Wire up your class to VBA in VSTO

    Private Sub ThisWorkbook_Open() Handles Me.Open
        Me.Application.Run("RegisterCallback", New MyManagedFunctions)
    End Sub
    

    Create Hook for managed code and a wrapper for the functions in VBA

    In a VBA module in your spreadsheet or document

    Dim managedObject As Object
    
    Public Sub RegisterCallback(callback As Object)
        Set managedObject = callback
    End Sub
    
    Public Function GetNumberFromVSTO() As Integer
        GetNumberFromVSTO = managedObject.GetNumber()
    End Function
    

    Now you can enter =GetNumberFromVSTO() in a cell, when excel starts the cell value should be 42.

    http://blogs.msdn.com/b/pstubbs/archive/2004/12/31/344964.aspx

提交回复
热议问题