C# : Excel : Determine if a string is a valid Range reference?

核能气质少年 提交于 2019-12-12 02:06:23

问题


How would this VB function will look like as C# ? The goal is to determine if a string ref represents a valid datasheet Excel.Range. This isn't a trivial VB to C# conversion as Range can't be constructed.

Private Function IsRange(ref) As Boolean
'   Returns True if ref is a Range
    Dim x As Range
    On Error Resume Next
    Set x = Range(ref)
    If Err = 0 Then IsRange = True Else IsRange = False
End Function

Best


回答1:


I would have liked to find a way to not have to rely on an exception for checking the validity of a cell reference. But I couldn't not find a way to directly test for it.

So instead I am using the OP's approach. The problem is that Microsoft.Office.Interop.Excel.Range is an interface and can't be directly created. Per this answer the solution is to use the get_Range method from _Application or Sheet.

Microsoft.Office.Interop.Excel._Application ExcelApp;

private bool IsRange(string refr) {
   try {
      var unused = ExcelApp.Range[cellReference, Type.Missing];

      return true;
   }
   catch {
      return false;
   }
}


来源:https://stackoverflow.com/questions/13871480/c-sharp-excel-determine-if-a-string-is-a-valid-range-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!