8

ブルームバーグのBDHの動作をコピーしたいと思います。

BDHはWeb要求を行い、配列を書き込みます(ただし、配列スタイルは返しません)。このWebリクエスト中に、関数は「#N/Aリクエスト」を返します。Webリクエストが終了すると、BDH()関数は配列の結果をワークシートに書き込みます。

たとえば、ExcelDNAでは、スレッドを使用してワークシートに書き込むことに成功しています。

DNAファイルで以下のコードを使用した場合の結果、

= WriteArray(2; 2)

になります

1行目>#N/A Requesting Data (0,1)

2行目>(1,0) (1,1)

最後の問題は、値に置き換え#N/A Requesting Dataて数式をコピーすることです。//xlActiveCellType.InvokeMember( "FormulaR1C1Local"のコメントを外すと、結果に近づきますが、正しい動作はありません

ファイル.dna

 <DnaLibrary Language="CS" RuntimeVersion="v4.0">
<![CDATA[

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using ExcelDna.Integration;


    public static class WriteForXL
    {

        public static object[,] MakeArray(int rows, int columns)
        {
            if (rows == 0 && columns == 0)
            {
                rows = 1;
                columns = 1;
            }


            object[,] result = new string[rows, columns];
            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < columns; j++)
                {
                    result[i, j] = string.Format("({0},{1})", i, j);
                }
            }

            return result;
        }

        public static object WriteArray(int rows, int columns)
        {
            if (ExcelDnaUtil.IsInFunctionWizard())
                return "Waiting for click on wizard ok button to calculate.";

            object[,] result = MakeArray(rows, columns);

            var xlApp = ExcelDnaUtil.Application;
            Type xlAppType = xlApp.GetType();
            object caller = xlAppType.InvokeMember("ActiveCell", BindingFlags.GetProperty, null, xlApp, null);
            object formula = xlAppType.InvokeMember("FormulaR1C1Local", BindingFlags.GetProperty, null, caller, null);

            ObjectForThread q = new ObjectForThread() { xlRef = caller, value = result, FormulaR1C1Local = formula };

            Thread t = new Thread(WriteFromThread);
            t.Start(q);            

            return "#N/A Requesting Data";
        }

        private static void WriteFromThread(Object o)
        {
            ObjectForThread q = (ObjectForThread) o;

            Type xlActiveCellType = q.xlRef.GetType();

            try
            {
                for (int i = 0; i < q.value.GetLength(0); i++)
                {
                    for (int j = 0; j < q.value.GetLength(1); j++)
                    {
                        if (i == 0 && j == 0)
                            continue;

                        Object cellBelow = xlActiveCellType.InvokeMember("Offset", BindingFlags.GetProperty, null, q.xlRef, new object[] { i, j });
                        xlActiveCellType.InvokeMember("Value", BindingFlags.SetProperty, null, cellBelow, new[] { Type.Missing, q.value[i, j] });             
                    }
                }                               
            }
            catch(Exception e)
            {                
            }
            finally
            {
                //xlActiveCellType.InvokeMember("Value", BindingFlags.SetProperty, null, q.xlRef, new[] { Type.Missing, q.value[0, 0] });
                //xlActiveCellType.InvokeMember("FormulaR1C1Local", BindingFlags.SetProperty, null, q.xlRef, new [] { q.FormulaR1C1Local });               
            }
        } 

public class ObjectForThread
        {
            public object xlRef { get; set; }
            public object[,] value { get; set; }
            public object FormulaR1C1Local { get; set; }
        }

    }

    ]]>

</DnaLibrary>

@Govertへ

BDHは金融業界の標準になりました。人々は配列を操作する方法を知りません(Ctrl + Shift + Enterでさえ)。

BDHは、ブルームバーグを非常に人気のあるものにした機能です(ロイターの不利な点に)。

しかし、私はあなたの方法またはRTDを使用することを考えます。

ExcelDNAでのすべての作業に感謝します

4

4 に答える 4

7

Excel-DNA ArrayResizerサンプルを試したことがあると思います。これにより、発生している問題の多くを慎重に回避できます。配列式を書くアプローチの不利な点としてあなたが見ているものを理解したいと思います。

さて、あなたの機能について:

まず、「呼び出し元」の範囲COMオブジェクトを別のスレッドに安全に渡すことはできません。アドレスを含む文字列を渡し、他のスレッドからCOMオブジェクトを取得します(ワーカースレッドでExcelDnaUtil.Applicationを呼び出します)。ただし、ほとんどの場合、幸運に恵まれます。これを行うためのより良い方法は、ワーカースレッドからExcelにメインスレッドでマクロを実行させることです-Application.Runを呼び出します。Excel-DNA ArrayResizerサンプルは、これを行う方法を示しています。

次に、ActiveCellではなく、Application.Callerが必要になることはほぼ間違いありません。ActiveCellは、数式が実行されているセルとは何の関係もない可能性があります。

次へ-数式を再度設定するたびにExcelが関数を再計算するため、finally句で数式セットを有効にすると無限ループに陥ります。セルに値と数式の両方を設定することはできません。セルに数式がある場合、Excelは数式を使用して値を計算します。値を設定すると、数式が削除されます。[0,0]セルに実際に何を残したいかは明確ではありません-IIRCBloombergは、範囲が書き込まれた範囲を記憶するように数式を変更します。関数に再計算するかどうか、または結果として実際の値を返すかどうかを指示するパラメーターを関数に追加してみることができます。

最後に、ブルームバーグBDH関数が自分のやりたいことの良い例であるかどうかを再考することをお勧めします。シートの依存関係の計算が中断され、パフォーマンスとスプレッドシートモデルの一貫性の維持の両方に影響があります。

于 2012-03-13T08:41:55.850 に答える
2

私の問題は:

  • 動的配列の書き込み

  • データはWebサービスを介して非同期で取得されます

Govertと話し合った後、結果を配列として取得し、Bloomberg関数をコピーしないことを選択しました(配列を記述しますが、単一の値を返します)。

最後に、問題を解決するために、http: //excel-dna.net/2011/01/30/resizing-excel-udf-result-arrays/を使用して、resize()関数の形状を変更しました。

このコードはRTDではありません。

以下のコードは.dnaファイルで機能します

<DnaLibrary RuntimeVersion="v4.0"  Language="C#">
<![CDATA[
    using System;
    using System.Collections.Generic;
    using System.Reflection;
    using System.Runtime.InteropServices;
    using System.Threading;
    using System.ComponentModel;
    using ExcelDna.Integration;

    public static class ResizeTest
    {
        public static object[,] MakeArray(int rows, int columns)
        {
            object[,] result = new string[rows, columns];
            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < columns; j++)
                {
                    result[i,j] = string.Format("({0},{1})", i, j);
                }
            }

            return result;
        }

        public static object MakeArrayAndResize()
        {         
            // Call Resize via Excel - so if the Resize add-in is not part of this code, it should still work.
            return XlCall.Excel(XlCall.xlUDF, "Resize", null);
        }
    }

    public class Resizer
    {
        static Queue<ExcelReference> ResizeJobs = new Queue<ExcelReference>();
        static Dictionary<string, object> JobIsDone = new Dictionary<string, object>();

        // This function will run in the UDF context.
        // Needs extra protection to allow multithreaded use.
        public static object Resize(object args)
        {
            ExcelReference caller = XlCall.Excel(XlCall.xlfCaller) as ExcelReference;
            if (caller == null)
                return ExcelError.ExcelErrorNA;

            if (!JobIsDone.ContainsKey(GetHashcode(caller)))
            {
                BackgroundWorker(caller);
                return ExcelError.ExcelErrorNA;
            }
            else
            {
                // Size is already OK - just return result
                object[,] array = (object[,])JobIsDone[GetHashcode(caller)];
                JobIsDone.Remove(GetHashcode(caller));
                return array;
            }
        }

        /// <summary>
        /// Simulate WebServiceRequest
        /// </summary>
        /// <param name="caller"></param>
        /// <param name="rows"></param>
        /// <param name="columns"></param>
        static void BackgroundWorker(ExcelReference caller)
        { 
            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += (sender, args) =>
            {
                Thread.Sleep(3000);
            };
            bw.RunWorkerCompleted += (sender, args) =>
            {
                // La requete
                Random r = new Random();
                object[,] array = ResizeTest.MakeArray(r.Next(10), r.Next(10));

                JobIsDone[GetHashcode(caller)] = array;
                int rows = array.GetLength(0);
                int columns = array.GetLength(1);
                EnqueueResize(caller, rows, columns);
                AsyncRunMacro("DoResizing");
            };

            bw.RunWorkerAsync();
        }

        static string GetHashcode(ExcelReference caller)
        {
            return caller.SheetId + ":L" + caller.RowFirst + "C" + caller.ColumnFirst;
        }


        static void EnqueueResize(ExcelReference caller, int rows, int columns)
        {
            ExcelReference target = new ExcelReference(caller.RowFirst, caller.RowFirst + rows - 1, caller.ColumnFirst, caller.ColumnFirst + columns - 1, caller.SheetId);
            ResizeJobs.Enqueue(target);
        }

        public static void DoResizing()
        {
            while (ResizeJobs.Count > 0)
            {
                DoResize(ResizeJobs.Dequeue());
            }
        }

        static void DoResize(ExcelReference target)
        {
            try
            {
                // Get the current state for reset later

                XlCall.Excel(XlCall.xlcEcho, false);

                // Get the formula in the first cell of the target
                string formula = (string)XlCall.Excel(XlCall.xlfGetCell, 41, target);
                ExcelReference firstCell = new ExcelReference(target.RowFirst, target.RowFirst, target.ColumnFirst, target.ColumnFirst, target.SheetId);

                bool isFormulaArray = (bool)XlCall.Excel(XlCall.xlfGetCell, 49, target);
                if (isFormulaArray)
                {
                    object oldSelectionOnActiveSheet = XlCall.Excel(XlCall.xlfSelection);
                    object oldActiveCell = XlCall.Excel(XlCall.xlfActiveCell);

                    // Remember old selection and select the first cell of the target
                    string firstCellSheet = (string)XlCall.Excel(XlCall.xlSheetNm, firstCell);
                    XlCall.Excel(XlCall.xlcWorkbookSelect, new object[] {firstCellSheet});
                    object oldSelectionOnArraySheet = XlCall.Excel(XlCall.xlfSelection);
                    XlCall.Excel(XlCall.xlcFormulaGoto, firstCell);

                    // Extend the selection to the whole array and clear
                    XlCall.Excel(XlCall.xlcSelectSpecial, 6);
                    ExcelReference oldArray = (ExcelReference)XlCall.Excel(XlCall.xlfSelection);

                    oldArray.SetValue(ExcelEmpty.Value);
                    XlCall.Excel(XlCall.xlcSelect, oldSelectionOnArraySheet);
                    XlCall.Excel(XlCall.xlcFormulaGoto, oldSelectionOnActiveSheet);
                }
                // Get the formula and convert to R1C1 mode
                bool isR1C1Mode = (bool)XlCall.Excel(XlCall.xlfGetWorkspace, 4);
                string formulaR1C1 = formula;
                if (!isR1C1Mode)
                {
                    // Set the formula into the whole target
                    formulaR1C1 = (string)XlCall.Excel(XlCall.xlfFormulaConvert, formula, true, false, ExcelMissing.Value, firstCell);
                }
                // Must be R1C1-style references
                object ignoredResult;
                XlCall.XlReturn retval = XlCall.TryExcel(XlCall.xlcFormulaArray, out ignoredResult, formulaR1C1, target);
                if (retval != XlCall.XlReturn.XlReturnSuccess)
                {
                    // TODO: Consider what to do now!?
                    // Might have failed due to array in the way.
                    firstCell.SetValue("'" + formula);
                }
            }
            finally
            {
                XlCall.Excel(XlCall.xlcEcho, true);
            }
        }

        // Most of this from the newsgroup: http://groups.google.com/group/exceldna/browse_thread/thread/a72c9b9f49523fc9/4577cd6840c7f195
        private static readonly TimeSpan BackoffTime = TimeSpan.FromSeconds(1); 
        static void AsyncRunMacro(string macroName)
        {
            // Do this on a new thread....
            Thread newThread = new Thread( delegate ()
            {
                while(true) 
                { 
                    try 
                    {
                        RunMacro(macroName);
                        break; 
                    } 
                    catch(COMException cex) 
                    { 
                        if(IsRetry(cex)) 
                        { 
                            Thread.Sleep(BackoffTime); 
                            continue; 
                        } 
                        // TODO: Handle unexpected error
                        return; 
                    }
                    catch(Exception ex) 
                    { 
                        // TODO: Handle unexpected error
                        return;
                    } 
                }
            });
            newThread.Start();
        }

        static void RunMacro(string macroName)
        {
            object xlApp = null;       
            try
            {
                xlApp = ExcelDnaUtil.Application;
                xlApp.GetType().InvokeMember("Run", BindingFlags.InvokeMethod, null, xlApp, new object[] {macroName});
            }
            catch (TargetInvocationException tie)
            {
                throw tie.InnerException;
            }
            finally
            {
                Marshal.ReleaseComObject(xlApp);
            }
        }

        const uint RPC_E_SERVERCALL_RETRYLATER = 0x8001010A; 
        const uint VBA_E_IGNORE = 0x800AC472; 
        static bool IsRetry(COMException e) 
        { 
            uint errorCode = (uint)e.ErrorCode; 
            switch(errorCode) 
            { 
                case RPC_E_SERVERCALL_RETRYLATER: 
                case VBA_E_IGNORE: 
                    return true; 
                default: 
                    return false; 
            }
        }
    } 
]]>
</DnaLibrary>
于 2012-03-23T08:12:48.100 に答える
0

リクエストをRTDサーバーとして実装する必要があると思います。通常のユーザー定義関数は非同期的に更新されません。
次に、Excel-DNAを介して実行できるユーザー定義関数を介してRTDサーバーの呼び出しを非表示にすることができます。

于 2012-03-12T14:17:40.207 に答える
-2

最後に、配列数式を使用しますよね?あなたが言ったように、ユーザーは配列数式に精通しておらず、ctrl + shift+enterを知りません。配列式は彼らにとって大きな問題だと思います。

私にとっても同じ問題があります。私はそれのプロトタイプを作ろうとしています。https://github.com/kchen0723/ExcelAsync.gitを参照して ください

于 2016-05-19T21:19:17.677 に答える