3

我有一些代码来替换 excel 项目中的文本(发布在下面),这段代码就像一个魅力。但我也希望替换文本实例的数量。有没有办法得到它?

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

1 回答 1

2

您不能直接执行此操作,但您可以运行FindFindNext运行,然后替换在搜索中找到的任何内容。这将为计算替换计数打开一个范围。

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
于 2012-08-22T18:30:05.470 回答