C# 如何知道是成功还是失败?
你不能这样做。如果参数正确,范围的替换方法总是返回true。我知道你能做的唯一一件事就是先查找你的文本,然后替换它。当然没有优化,但我想不出其他的东西C# 如何知道是成功还是失败?,c#,excel-interop,C#,Excel Interop,你不能这样做。如果参数正确,范围的替换方法总是返回true。我知道你能做的唯一一件事就是先查找你的文本,然后替换它。当然没有优化,但我想不出其他的东西 bool rep = xlWorkSheet.Cells.Replace(textBox1.Text, textBox2.Text, Excel.XlLookAt.xlWhole,
bool rep = xlWorkSheet.Cells.Replace(textBox1.Text,
textBox2.Text,
Excel.XlLookAt.xlWhole,
Excel.XlSearchOrder.xlByRows,
false,
Type.Missing,
Type.Missing,
Type.Missing);
以下代码可以正常工作:
bool rep = xlWorkSheet.Cells.Find(textBox1.Text,
Type.Missing,
Type.Missing,
Excel.XlLookAt.xlWhole,
Excel.XlSearchOrder.xlByRows,
Type.Missing,
false,
Type.Missing,
Type.Missing) != null;
if (rep)
xlWorkSheet.Cells.Replace(textBox1.Text,
textBox2.Text,
Excel.XlLookAt.xlWhole,
Excel.XlSearchOrder.xlByRows,
false,
Type.Missing,
Type.Missing,
Type.Missing);
除非您给出了错误的替换标准,否则它始终是成功的。在这种情况下,它将失败。但它在所有情况下都返回true…您真的想知道“替换了多少次”吗?不,如果替换发生在一张工作表中,我需要该工作表的名称(int i=1;我是的,这基本上是我的答案…但你说你想替换文本并知道它是否在那里。这样你只知道字符串是否在你的shhets中找到。在你的答案中,你将xlsheet.Cells.find设置为bool,但它返回Range…在编辑中有一个!=null,我在从VS复制时忘记了它…但我还是不明白你是否想更换一些东西
Excel.Range Range = xlWorkSheet.UsedRange;
currentFind = Range .Find(textBox1.Text, Type.Missing,Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows,Excel.XlSearchDirection.xlNext,false,
Type.Missing, Type.Missing);
if (currentFind!=null)
{
SheetsArray.Add(xlWorkSheet.Name);
}