如何在整个工作簿中搜索文本?



我需要在Excel文件中搜索特定文本。

我在MS上找到了这篇文章。 https://learn.microsoft.com/en-us/visualstudio/vsto/how-to-programmatically-search-for-text-in-worksheet-ranges?view=vs-2019 我修改了它以搜索整个工作簿。 它工作正常,直到只有一个具有搜索值的工作表。如果任何其他工作表也具有该值,则 Excel 将使用沙漏指针冻结。最终,我需要杀死这个过程。

这是我的代码:

public int searchcount(string srchtrm)
{
Excel.Range currentFind = null;
Excel.Range firstFind = null;
int stcount = 0;
foreach (Excel.Worksheet w in Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets)
{
w.Select();   
Excel.Range Fruits = w.UsedRange;
currentFind = Fruits.Find(srchtrm, Type.Missing,
Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart,
Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false,
Type.Missing, Type.Missing);
while (currentFind != null)
{
if (firstFind == null)
{
firstFind = currentFind;
}
else if (currentFind.get_Address(Excel.XlReferenceStyle.xlA1)
== firstFind.get_Address(Excel.XlReferenceStyle.xlA1))
{
break;
}
currentFind.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
currentFind.Font.Bold = true;
currentFind = Fruits.FindNext(currentFind);
stcount = stcount + 1;
}
}
return stcount;
}

您不会重置currentFindfirstFind变量。这会导致无限循环,因为一旦工作簿中有超过 1 张工作表,您就会使用上一张工作表中的currentFindfirstFind值。

最简单的解决方案是在内部循环中声明这些变量:

int stcount = 0;
foreach (Excel.Worksheet w in Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets)
{
Excel.Range currentFind = null;
Excel.Range firstFind = null;
w.Select();   
Excel.Range Fruits = w.UsedRange;
// REST of the code....
}

最新更新