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

问题描述 投票:1回答:1

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

我在MS上找到了这篇文章。https://docs.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;
    }
c# excel vsto interop office-interop
1个回答
1
投票
您未重置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.... }

© www.soinside.com 2019 - 2024. All rights reserved.