How to get the Range object in the Excel UDF function.

I use .net to develop the Excel udf function with the following requirements: inside the udf function, get the range object of the cell currently calling the udf function. I now use the following code to get it, although I can get it, but there is a bug: when multiple excel is opened, or throw a COMException, exception from HRESULT:0x800A03EC

Microsoft.Office.Interop.Excel.Application app =
(Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
            Microsoft.Office.Interop.Excel.Range rr = app.ThisCell;

I would like to ask you if there is any other way to get the Range object.

May.11,2021

after looking for a day to solve it myself, the udf class implements the interface IDTExtensibility2, and then overrides the following methods

public void OnConnection(object Application, ext_ConnectMode ConnectMode, 
object objectAddInInst, ref Array custom)
  {
    MyExcelAppInstance = (MsExcel.Application)Application;
    MyAddInInstance = AddInInst;
  }

MyExcelAppInstance is the excel instance of the currently executed udf function

Menu