首页 > 解决方案 > Range.Find 返回 null 并且无法识别 Count 方法

问题描述

我已经检查了相关问题,没有得到任何进一步的见解。我也是 C# 的新手。你能帮我吗 - 我希望这是一个简单的操作,在另一张纸上找到一个值,然后提取该值/字符串的行。

我有以下代码总是为Rowx返回“null” 。另外,我拥有的程序集无法识别计数/长度。System.Core 无法添加,据说它已经是构建的一部分。我正在使用 vs 2019,.Net 4.5。

    [STAThread]
    public static void Main(string[] args)
    {  
        Excel.Application excel = new Excel.Application();  // Opening and labelling source workbook
        Excel.Workbook Copt = excel.Workbooks.Open(Reportpath);
        Worksheet x = Copt.Worksheets["PD"];  //labeling worksheets
        Worksheet y = Copt.Worksheets["Data"];
        
        // recreating and naming the source two sheets which we will manipulate later
        var index = x.Index;
        x.Copy(Before: x);
        Worksheet WPDss = (Worksheet)excel.Worksheets[index];
        WPDss.Name = "WPs";

        var index1 = y.Index;
        y.Copy(Before: y);
        Worksheet Datass = (Worksheet)excel.Worksheets[index1];
        Datass.Name = "WPData";

        Range Rangex = WPDss.Range["G3:G30"];   // Creating ranges using "WPs" and "WPData"
        Range Rangey = Datass.UsedRange;

        Range Rowx;
        //initiating total rows and columns for "WPData"
        int totcoly = Rangey.Column.Count; //Count not recognized
        int totrowy = Rangey.Row.Length; // Length not recognized

        int iterx = 50;  // initiating number of iterations 
       
        object[,] Objx = Rangex.Value;  // creating objects for the ranges
        object[,] Objy = Rangey.Value;

        for (int i = 1; i < iterx;i++)
        {
            try
            { // trying to find the Row in "Rangex" corresponding to the value in "Objy[i,50]"
                 Rowx = Rangex.Find(Rangey[i, 50].Value).Row; //ALWAYS RETURNING NULL

              // If Rowx is null then throw an exception, otherwe implemement the following operation
                if (Rowx != null && Rangey[i, 50].ToString() == Rangex[Rowx, 7].ToString())
                {
                    WPDss.Cells[i, 9] = (dynamic)Rangey[Rowx, 1];
                }
            }
            catch (Exception)
            {
                // MessageBox.Show("Ayikho lento ndoda");
            }
         }
     }
  }

}

标签: c#excel-interop

解决方案


推荐阅读