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

excel – C# Exception User-Unhandled

Posted by: admin May 14, 2020 Leave a comment

Questions:

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)
                    {
                        count++;
                        Excel.Range start = first;
                        do
                        {
                            start.Value = replacement;
                            count++;
                            start = r.FindNext(m);                            
                            xlWorkBook.Save();

                        }
                        while (start != first);
                    }
                }

                xlWorkBook.Close();
            }

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

System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=<Cannot evaluate the exception source>
  StackTrace:
<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.