以编程方式搜索工作表区域中的文本

对象 Find 的方法 Range 使你能够在范围内搜索文本。 此文本也可以是可在工作表单元格中显示的任何错误字符串,例如 #NULL!#VALUE!。 有关错误字符串的详细信息,请参阅 单元格错误值

适用于: 本主题中的信息适用于 Excel 的文档级项目和 VSTO 外接程序项目。 有关详细信息,请参阅办公室应用程序和项目类型提供的功能。

以下示例搜索一个命名 Fruits 区域,并修改包含单词“apples”的单元格的字体。 此过程还使用 FindNext 该方法,该方法使用以前设置的搜索设置重复搜索。 指定要在其中搜索的单元格,该方法 FindNext 将处理其余部分。

注意

方法 FindNext 的搜索在到达范围末尾后,将回退到搜索范围的开头。 代码必须确保搜索不会在无限循环中环绕。 示例过程显示了使用属性处理此方法的 Address[] 一种方法。

在工作表区域中搜索文本

  1. 声明用于跟踪整个范围的变量、第一个找到的范围和当前找到的范围。

    Excel.Range currentFind = null; 
    Excel.Range firstFind = null;
    
  2. 搜索第一个匹配项,指定要搜索的单元格以外的所有参数。

    currentFind = Fruits.Find("apples", missing,
        Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart, 
        Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false,
        missing, missing);
    
  3. 只要存在匹配项,继续搜索。

    while(currentFind != null)
    
  4. 将第一个找到的范围 (firstFind) 与 Nothing 进行比较。 如果 firstFind 不包含任何值,则代码会存储找到的范围(currentFind)。

    if (firstFind == null)
    {
        firstFind = currentFind; 
    }
    
  5. 如果找到区域的地址与第一个找到区域的地址匹配,请退出循环。

    else if (currentFind.get_Address(Excel.XlReferenceStyle.xlA1)
          == firstFind.get_Address(Excel.XlReferenceStyle.xlA1))
    {
        break;
    }
    
  6. 设置找到的范围的外观。

    currentFind.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
    currentFind.Font.Bold = true;
    
  7. 执行另一个搜索。

    currentFind = Fruits.FindNext(currentFind);
    

    以下示例显示完整的方法。

示例

    private void DemoFind() 
    {
        Excel.Range currentFind = null; 
        Excel.Range firstFind = null; 

        Excel.Range Fruits = Application.get_Range("A1", "B3");
        // You should specify all these parameters every time you call this method,
        // since they can be overridden in the user interface. 
        currentFind = Fruits.Find("apples", missing,
            Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart, 
            Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false,
            missing, missing); 

        while(currentFind != null) 
        { 
            // Keep track of the first range you find. 
            if (firstFind == null)
            {
                firstFind = currentFind; 
            }

            // If you didn't move to a new range, you are done.
            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); 
        }
    }