Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating new Excel formulas/functions with C#

We are looking to be able to programmatically create an Excel workbook which would call custom code from within a cell. Cells would look something like:

=MyCode(A1:A10)

My first thought was to use VBA, but since the algorithm is proprietary the powers that be want it to be protected. I can put a password on it, but it is well documented (here on StackOverflow) on how to get around such passwords.

My second thought was to create an Excel 2013 Workbook project in Visual Studio, but I haven't found anything useful on how to expose a function in C# so it can be called like I described.

Next I thought about having VBA call the C#, and found instructions at https://msdn.microsoft.com/en-us/library/bb608613.aspx. I followed those instructions to the letter, but when I try to run the VBA code I get an error with the GetManagedClass function: Object Library Feature not Supported.

Are there any good references on how to do something like this?

like image 508
Walter Williams Avatar asked Mar 18 '15 20:03

Walter Williams


People also ask

Can you make Excel formulas using functions?

You can create a formula to calculate values in your worksheet by using a function. For example, the formulas =SUM(A1:A2) and SUM(A1,A2) both use the SUM function to add the values in cells A1 and A2. Formulas always start with an equal sign (=). Click the cell where you want the formula.

Can you use C with Excel?

The Excel C API is the ideal choice when you want to create high-performance worksheet functions by creating XLL add-ins. The C API provides you with the most direct access to worksheet data. XLLs provide Excel with the most direct access to the DLL resources.

How do you add C in Excel?

Using a Keyboard Shortcut Use the keyboard shortcut – ALT + 0176 (you need to hold the ALT key and then press 0176 from the numeric keypad of your keyboard).


1 Answers

You're looking for Excel-DNA. This open-source library allows you to create managed Excel add-ins, and supports making user-defined functions, but also macros, real-time RTD data sources etc.

Creating an Excel UDF in C# is then as simple as:

[ExcelFunction(Description = "My first .NET function")]
public static string SayHello(string name)
{
    return "Hello " + name;
}

and you can call from a cell as:

=SayHello("Walter")

For code protection with .NET, you'd need to use an obfuscator - there are a variety of free and paid-for ones available.

like image 133
Govert Avatar answered Oct 19 '22 05:10

Govert