C#-Can';t在Excel文件中替换句子中的文本

C#-Can';t在Excel文件中替换句子中的文本,c#,excel,excel-interop,C#,Excel,Excel Interop,我编写了一个代码来替换excel文件中的文本。但问题是,如果在一个句子中找到文本,则该代码不会替换文本。我做错什么了吗?在Word文档中,我可以通过将MatchWholeWord标志更改为false来修复此问题。这是我的密码: static void ReplaceTextInExcelFile1(string filename, string replace, string replacement) { object m = Type.Missing;

我编写了一个代码来替换excel文件中的文本。但问题是,如果在一个句子中找到文本,则该代码不会替换文本。我做错什么了吗?在Word文档中,我可以通过将MatchWholeWord标志更改为false来修复此问题。这是我的密码:

 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;
        }
static void replacettextinexcelfile1(字符串文件名、字符串替换、字符串替换)
{
对象m=类型。缺少;
//打开excel。
Excel.Application app=新建Excel.Application();
//打开工作簿。
工作簿wb=app.Workbooks.Open(
文件名,
m、 假,m,m,m,m,m,m,m,m,m,m,m,m,m;
//获取活动工作表。(如果需要,请替换此工作表。)
工作表ws=null;
范围r=null;
app.DisplayAlerts=false;
对于(int x=0;x
快速搜索一下
XlLookAt.xlWhole
会让人觉得这就是罪魁祸首。请尝试
XlLookAt.xlPart
,它可能与您提到的
matchWholeWord
等效。因此基本上
XlLookAt.xlother
检查每个单元格的全部内容,这些内容必须与要替换的字符串完全匹配,而
XlLookAt.xlPart
允许替换子字符串。您的建议奏效了。非常感谢。