How to pass a Range object in an Excel Formula cre

2019-08-20 08:49发布

问题:

I have created an Excel Formula using help from this link: Canonical: How to call .NET methods from Excel VBA

It is working fine, but now I have a requirement of sending an Excel Range Object to this formula, to C# and operate on that range. Every time I try to do this, it gives me "#Value!" error.

How do I do this?

(I am writing the code for the formula in the C# end and not in the VBA. Please mind that.)

I have tried using normal "Microsoft.Office.Interop.Excel.Range" object.

namespace FormulaAddin
    {
    [Guid("29A34EFD-B8A3-48D8-847A-4BF402831617")]
    [ClassInterface(ClassInterfaceType.AutoDual)]
    [ComVisible(true)]
    public class Formulae
        {

        public Formulae ()
            {
            }

        public int CountRange(Excel.Range nRange)
            {            
            //Some code working on the range
            }       

        #region Registering COM Object

        [ComRegisterFunction]
        public static void RegisterFunction (Type type)
            {
            Registry.ClassesRoot.CreateSubKey(GetSubKeyName(type, "Programmable"));
            RegistryKey key = Registry.ClassesRoot.OpenSubKey(GetSubKeyName(type, "InprocServer32"), true);
            key.SetValue("", Environment.SystemDirectory + @"\mscoree.dll", RegistryValueKind.String);
            }

        [ComUnregisterFunction]
        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();
            }

        #endregion
        }
    }