Home » excel » C# Excel Interop Count and Replace

C# Excel Interop Count and Replace

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have some code to replace text in an excel project(posted below), this code works like a charm. But I also want the number of text instances replaced.
Is there any way to get that?

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

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

// 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 = (Worksheet)wb.ActiveSheet;

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

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

// save and close. 
wb.Save();
app.Quit();
app = null;
}
How to&Answers:

You cant do it directly, but you can run Find and FindNext function and then replace whatever was found in the search.This will open a scope for taking the count of replacements.

Range r = (Range)ws.UsedRange;
int count=0;

Range first=r.Find(replace,m,m,XlLookAt.xlWhole,XlSearchOrder.xlByRows,m,m,m,m);
if(first!=null)
{count++;
Range start=first;
do
{
  start.Value=replacement;
  count++;
  start=r.FindNext(m);
}
while(start!=first);

//do whatever with count