简体   繁体   中英

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

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

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;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM