Range.Find - 类型不匹配。在搜索长字符串时

时间:2018-02-19 14:21:07

标签: vsto excel-interop

在C#VSTO for excel中,当我在非常长的字符串上使用Find方法时,我得到:

Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))

任何想法?

1 个答案:

答案 0 :(得分:0)

用Excel& amp;谷歌搜索我发现Find有255个字符的限制 - 您可以按CTRL-F并看到输入是有限的。

我无法找到有关该限制的Microsoft文档。 所以这是C#中的变通方法扩展方法:

   public static Range FindLongStr(this Range rng, 
                                        string what,
                                        object after,
                                        object lookIn, 
                                        object lookAt, 
                                        object searchOrder, 
                                        XlSearchDirection searchDirection = XlSearchDirection.xlNext,
                                        object matchCase = null,
                                        object matchByte = null,
                                        object searchFormat = null){
       Range retVal;
       if (what.Length < 255)
       {
          retVal = rng.Find(what, after, lookIn, lookAt, searchOrder, searchDirection, matchCase, matchByte, searchFormat);
       }
       else
       {
          var whatSearch = what.Substring(0, 254) + "*";
          retVal = rng.Find(whatSearch, after, lookIn, lookAt, searchOrder, searchDirection, matchCase, matchByte, searchFormat);
          while (retVal != null && retVal.Cells.Value2 != what)
          {
             retVal = rng.Find(whatSearch, retVal, lookIn, lookAt, searchOrder, searchDirection, matchCase, matchByte, searchFormat);
          }
       }
       return retVal;
    }