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?
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With