C#Excel互操作计数和replace

我有一些代码来replaceexcel项目中的文本(下面发布),这个代码就像一个魅力。 但是我也想要replace文本实例的数量。 有什么办法可以得到吗?

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; } 

你不能直接做,但你可以运行FindFindNext函数,然后replaceFind任何内容。这将打开一个取代计数的范围。

 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