I am developing an excel add in with my following code .
I created a Class library and added the following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace MyCustomAutomation
{
// Replace the Guid below with your own guid that
// you generate using Create GUID from the Tools menu
[Guid("5268ABE2-9B09-439d-BE97-2EA60E103EF6")]
[ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
public class MyFunctions
{
public MyFunctions()
{
}
public double MultiplyNTimes(double number1, double number2, double timesToMultiply)
{
double result = number1;
for (double i = 0; i < timesToMultiply; i++)
{
result = result * number2;
}
return result;
}
[ComRegisterFunctionAttribute]
public static void RegisterFunction(Type type)
{
Registry.ClassesRoot.CreateSubKey(
GetSubKeyName(type, "Programmable"));
RegistryKey key = Registry.ClassesRoot.OpenSubKey(
GetSubKeyName(type, "InprocServer32"), true);
key.SetValue("",
System.Environment.SystemDirectory + @"\mscoree.dll",
RegistryValueKind.String);
}
[ComUnregisterFunctionAttribute]
public static void UnregisterFunction(Type type)
{
Registry.ClassesRoot.DeleteSubKey(
GetSubKeyName(type, "Programmable"), false);
}
private static string GetSubKeyName(Type type,
string subKeyName)
{
System.Text.StringBuilder s =
new System.Text.StringBuilder();
s.Append(@"CLSID\{");
s.Append(type.GUID.ToString().ToUpper());
s.Append(@"}\");
s.Append(subKeyName);
return s.ToString();
}
}
}
I installed it and the Function works fine in excel .I am able to use MultiplyNTimes function that returns the value.However my issue is that when i call the function from the cell the result is displayed in the same cell itself whereas I want the result to be played in any cell other than the called cell.I am totally clueless as I cannot reach any direction.
Please help
To have the result in another cell, simply return the result as an array. So as an example for another version of your MultiplyNTimes function, this can be written as:
And then when you use this function in Excel, you must use the array formula syntax, which means if you enter the function in A1, then select both cells A1 and B1, then press F2 and then Ctrl+Shift+Enter
Also note, I have simply used 0 to be returned in the cell where the formula is entered. If you wish to change this to another value of different types, you can use an array of object as the result data type.
So for example, you can rewrite it in this way: