다음을 통해 공유


프로그래밍 방식으로 워크시트 범위에서 텍스트 검색

Range 개체의 Find 메서드를 사용하면 범위 내에서 텍스트를 검색할 수 있습니다. 이 텍스트는 #NULL! 또는 #VALUE!와 같은 워크시트 셀에 표시될 수 있는 오류 문자열일 수도 있습니다. 오류 문자열에 대한 자세한 내용은 셀 오류 값을 참조하세요.

적용 대상: 이 항목의 정보는 Excel의 문서 수준 프로젝트 및 VSTO 추가 기능 프로젝트에 적용됩니다. 자세한 내용은 Office 애플리케이션 및 프로젝트 형식에 따라 사용 가능한 기능을 참조하세요.

다음 예제에서는 이름이 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); 
        }
    }