简体   繁体   中英

How to disable formula error check in Excel programmatically

I try to set formula to Excel cell in C# in several steps, however during the process I set it, it seems Excel throws exception due to invalid formula. I wonder how can I turn off the formula error check in C#. thanks

Edit The formula is too long, longer than 255 characters. So I can't set formula in one step. Have to set a short formula, then replace see http://netoffice.codeplex.com/discussions/402947

see code below but I get an error in rng.Formula = onePart;

where Constants.CUT_LENGTH = 253, Constants.MAX_FORMULA_LENGTH = 255, Separator = "||" I try to set EvaluateToError to false, still get an error

                XLApp.ErrorCheckingOptions.InconsistentFormula = false;
                XLApp.ErrorCheckingOptions.EvaluateToError = false;

                SetFormula(rangeFunction, formula);  


    public static void SetFormula(Range rng, string origFormula)
    {
        int i = 0;
        foreach (var onePart in CutStringIntoSubstrings(origFormula))
        {                
            if(i==0)
            {
                rng.Formula = onePart;
                i++;
            }
            else
            {
                rng.Replace(Constants.Separator, onePart);
            }
        }
    }
    public static IEnumerable<string> CutStringIntoSubstrings(string origFormula)
    {
        if (origFormula == null) yield return string.Empty;
        if (string.IsNullOrEmpty(origFormula)) yield return string.Empty;
        if (origFormula.Length <= Constants.MAX_FORMULA_LENGTH) yield return origFormula;

        int startIdx = 0;
        int endIdx = startIdx + Constants.CUT_LENGTH;
        while(endIdx < origFormula.Length)
        {
            var substr = origFormula.Substring(startIdx, Constants.CUT_LENGTH);
            if(startIdx + Constants.CUT_LENGTH < origFormula.Length)
            {
                substr += Constants.Separator;
            }
            yield return substr;
            startIdx += Constants.CUT_LENGTH;
            endIdx = startIdx + Constants.CUT_LENGTH;
        }
        if (startIdx < origFormula.Length) yield return origFormula.Substring(startIdx);
    }

You can refer to this article

http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.errorcheckingoptions_members.aspx http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.error.ignore(v=office.11).aspx

May b it might help :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM