1

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.

Chen
  • 860
  • 10
  • 32
  • 1
    `start = r.FindNext(m)` returns a `null` value at some point. Debug this step by step. – lordvlad30 Dec 17 '19 at 16:47
  • 1
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it), if not have you debugged your code? – Trevor Dec 17 '19 at 16:53
  • Yes, the answer provided by @vasil oreshenski was right on point. – Chen Dec 17 '19 at 17:55

1 Answers1

2

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.

vasil oreshenski
  • 2,788
  • 1
  • 14
  • 21