【问题标题】:Getting the previous cells of a given data range获取给定数据范围的前一个单元格
【发布时间】:2015-07-15 09:04:14
【问题描述】:

我尝试获取给定范围的先前单元格。到目前为止,我的代码如下所示:

获取选定的范围并将其传递给另一个方法

Microsoft.Office.Interop.Excel._Application app = this.ExcelAppObj as Microsoft.Office.Interop.Excel._Application;
Microsoft.Office.Interop.Excel.Range range = null;

range = app.get_Range(this.DataRangeTextBox.Text);
var caption = ExcelHelper.GetRangeHeaderCaption(range);

下面的方法被执行

 /// <summary>
    /// Gets the range header caption of a given range.
    /// The methode goes through every previous cell of the given range to determine the caption.
    /// If the caption can not be determined the method returns an random string.
    /// </summary>
    /// <param name="selectedRange">The selected range.</param>
    /// <returns></returns>
    public static string GetRangeHeaderCaption(Range selectedRange, Microsoft.Office.Interop.Excel._Application excelApp)
    {
        // The caption of the range. The default value is a random string
        var rangeCaption = ExcelHelper.getRandomString(5);                      

        // Check if the provided range is valid
        if (selectedRange != null && excelApp.WorksheetFunction.CountA(selectedRange) > 0)
        {
            var captionNotFound = true;
            Range rangeToCheck = selectedRange.Previous;

            // Go to each previous cell of the provided range 
            // to determine the caption of the range            
            do
            {
                // No further previous cells found
                // We can stop further processing
                if (rangeToCheck.Cells.Count == 0)
                {
                    break;
                }

                //System.Array myvalues = (System.Array)rangeToCheck.Cells.Value;
                System.Array myvalues = (System.Array)rangeToCheck.Cells.Value;

                rangeToCheck = rangeToCheck.Previous;

            } while (captionNotFound);
        }

        return rangeCaption;
    }

此时

var rangeToCheck = selectedRange.Previous;

属性访问引发以下异常:

A first chance exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll

Additional information: Die Previous-Eigenschaft des Range-Objektes kann nicht zugeordnet werden.

我想要达到的目标: 遍历给定数据范围的所有先前包含 double 或 int 值的单元格,并通过检查前一个单元格是数值还是字符串来获取标题标题。如果单元格包含字符串,则将字符串返回给调用者。

编辑#1 也许这是一个重要的信息。 GetRangeHeaderCaption 方法在另一个类中实现。它不包含在我使用 Excel 互操作获取范围的类中。

编辑#2 发现了问题。 属性 Previous 返回给定范围的前一个 LEFT 单元格。例如,如果我的范围具有地址 B2:B16,则上一个属性返回地址 A2。因此,如果我尝试访问 A2:A16 的 Previous 属性,则会出现异常,因为 A 列之前没有列。

但我需要的是,如果我有 B2:B16 范围,我需要获取 B1 的内容。你能一直跟着我吗?

【问题讨论】:

  • 检查 SelectedRange 是否有一些有效值且不为空
  • @Akansha:通过使用 if 语句进行验证来扩展方法以获取范围标题标题。还是没有变化
  • 调试“Rage”的值,如果范围是 [0,0] 则不会有前一个单元格。
  • 我想我找到了问题,但它并没有帮助我完成这件事。请参阅我更新的问题。

标签: c# excel excel-interop


【解决方案1】:

好吧,我动了脑筋,想出了一个解决这个问题的办法。它是一种解决方法,我不知道是否有其他方法或更好的方法来解决这个问题 - 请在此处查看我的代码:

    using XLS = Microsoft.Office.Interop.Excel;

         /// <summary>
    /// Gets the range header caption of a given range.
    /// The methode goes through every previous cell of the given range to determine the caption.
    /// If the caption can not be determined the method returns an random string.
    /// </summary>
    /// <param name="selectedRange">The selected range.</param>
    /// <returns></returns>
    public static string GetRangeHeaderCaption(Range selectedRange, XLS._Application excelApp)
    {
        // The caption of the range. The default value is a random string
        var rangeCaption = ExcelHelper.getRandomString(5);

        // Check if the provided range is valid
        if (selectedRange != null && excelApp.WorksheetFunction.CountA(selectedRange) > 0)
        {
            // Get the included cells of the range
            var rangeCells = selectedRange.Address.Split(new char[] { ':' });
            // Get the beginning cell of the range
            var beginCell = rangeCells[0].Trim();
            // Get the column and row data of the cell
            var cellColumnRow = beginCell.Split(new char[] { '$' });
            // Split the beginning cell into the column and the row
            var cellColumn = cellColumnRow[1];
            var cellRow = Convert.ToInt32(cellColumnRow[2]);

            var captionNotFound = true;
            int i = 0;
            // Go to each previous cell of the provided range 
            // to determine the caption of the range            
            do
            {
                // Check if the next cell would be invalid
                var nextCellRow = cellRow - i;
                if (nextCellRow == 0)
                    break;
                // Create the cell coordinates to look at
                var cellToLook = string.Format("{0}{1}",
                                                cellColumn,
                                                nextCellRow);
                // Get the value out of the cell
                var cellRangeValue = ((XLS.Worksheet)((XLS.Workbook)excelApp.ActiveWorkbook).ActiveSheet).get_Range(cellToLook).Value;
                // ...just to be sure it does not crash
                if (cellRangeValue != null)
                {
                    // Convert the determined value to an string
                    var cellValue = cellRangeValue.ToString();

                    double value;
                    // Check if the cell value is not a numeric value
                    // Check if the cell value is not empty or null
                    if (!double.TryParse(cellValue, out value) &&
                        !string.IsNullOrWhiteSpace(cellValue) &&
                        !string.IsNullOrEmpty(cellValue))
                    {
                        // In this case we found the caption
                        rangeCaption = cellValue;
                        captionNotFound = false;
                    }
                }

                i++;

            } while (captionNotFound);
        }

        return rangeCaption;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    相关资源
    最近更新 更多