C# - Can't replace text in a sentence in Excel file

427 views Asked by At

I wrote a code to replace text in excel file. But the problem is that this code does not replace the text if the the text is found in a sentence. Am I doing something wrong ? In Word document i'm able to fix this by changing MatchWholeWord flag to false. Here is my code :

 static void ReplaceTextInExcelFile1(string filename, string replace, string replacement)
        {
            object m = Type.Missing;

            // open excel.
            Excel.Application app = new Excel.Application();

            // open the workbook. 
            Workbook wb = app.Workbooks.Open(
                filename,
                m, false, m, m, m, m, m, m, m, m, m, m, m, m);

            // get the active worksheet. (Replace this if you need to.) 

            Worksheet ws = null;
            Range r = null;
            app.DisplayAlerts = false;

            for (int x = 0; x < wb.Worksheets.Count; x++)
            {
                ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[x + 1];

                // get the used range. 
                r = (Range)ws.UsedRange;

                // call the replace method to replace instances. 
                bool success = (bool)r.Replace(replace, replacement, XlLookAt.xlWhole, XlSearchOrder.xlByRows,false, m, m, m);
            }

            // save and close. 
            wb.Save();
            app.Quit();
            app = null;
        }
0

There are 0 answers