Home » excel » excel – C# Exception User-Unhandled

excel – C# Exception User-Unhandled

Posted by: admin May 14, 2020 Leave a comment


I am building a C# Excel Add-on to replace string xxx to yyy and find files in batch in a given folder path:

     string replace = "xxx";
     string replacement = "yyy";

     foreach (FileInfo file in listOfFiles)
        foreach (Excel.Worksheet xlWorkSheet in xlWorkBook.Worksheets)
                    Excel.Range r = (Excel.Range)xlWorkSheet.UsedRange;                    

                    Excel.Range first = r.Find(replace, m, m, Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, m, m, m);
                    if (first != null)
                        Excel.Range start = first;
                            start.Value = replacement;
                            start = r.FindNext(m);                            

                        while (start != first);


But when I run the code, the start.Value = replacement pops an error of

  Message=Object reference not set to an instance of an object.
  Source=<Cannot evaluate the exception source>
<Cannot evaluate the exception stack trace>

I don’t see any problems with my code here. I already check if (first != null) before setting up start, so start will not be null.

How to&Answers:

Yes, you check for null, but you also have 2nd action which may lead to null.
This line will return null when there are no other matches

 start = r.FindNext(m);         

You should do your check after each re-asign of the start variable.