2014-04-11 34 views
1

我试图确定给定范围内的任何单元格是否有公式。无法获得两个单元格之间的距离

我使用下面的函数:

public bool noFormulas(Excel.Worksheet dataSheet) 
    { 
     Excel.Range beginRange=dataSheet.Cells[3, beginColumn]; 
     Excel.Range endRange=dataSheet.Cells[lastRow, endColumn]; 

     Excel.Range fullRange = dataSheet.Cells[beginRange,endRange]; 
     return fullRange.HasFormula == false; 
    } 

在那里我已经宣布与互操作:

using Excel = Microsoft.Office.Interop.Excel; 

的问题是,当执行分配的fullRange价值的声明,我得到 这个例外:

An unhandled exception of type 'System.Runtime.InteropServices.COMException' 
occurred in mscorlib.dll 
Additional information: Exception from HRESULT: 0x800A03EC 

beginRangeendRange都被成功填充;我不应该能够根据其开始和结束单元格来获得范围吗?

+1

尝试更改'dataSheet.Cells [beginRange,endRange];'到'dataSheet.Range [beginRange,endRange];'。也可以改为'fullRange.HasFormula',你应该循环遍历每个单元格,并检查它是否有公式(因为现在它检查范围内的_all_单元格是否具有公式) –

+0

这很有效,随意将它作为答案。 'fullRange.HasFormula'成功;我不明白如何通过单个单元循环会提高性能。 – sigil

+1

不知道'Microsoft.Office.Interop.Excel',但在VBA中(COM模型应该是相同的),Range(..)。HasFormula'在_all_单元格有公式时返回'TRUE'或'FALSE'或不。正如你在Q中所提到的,我试图确定给定范围内的任何单元格是否有公式。因此,为了确定_any_单元格是否具有公式,应该使用循环(至少在VBA中,现在无法在C#中检查它) –

回答

1

由于从评论跟进,你应该改变

dataSheet.Cells[beginRange,endRange]; 

dataSheet.Range[beginRange,endRange]; 

而且不是fullRange.HasFormula你应该遍历每个单元,并检查它的任何是否具有式(因为在您的原始代码,它检查是否所有范围内的单元格是否具有公式,还有当您将两个单元格与公式并且没有f ormulas,fullRange.HasFormula抛出异常)。所以,工作代码是:

public bool noFormulas(Excel.Worksheet dataSheet) 
{ 
    Excel.Range beginRange = dataSheet.Cells[3, beginColumn]; 
    Excel.Range endRange = dataSheet.Cells[lastRow, endColumn]; 

    Excel.Range fullRange = dataSheet.Range[beginRange, endRange]; 

    foreach (Excel.Range c in fullRange) 
    { 
     if (c.HasFormula) 
     { 
     return false; 
     } 
    } 
    return true; 
}