2012-10-24 4 views
1

doc (실제 doc, docx가 아닌) 파일을 생성해야하는데 "Word"자동화 (Word 2010)를 사용하는 것이 가장 좋습니다. 나는 열어 본 파일을 가지고 있고, 그 다음에 새로운 값으로 저장하기 전에 값을 바꿉니다. (예 : "CHRONO"를 "155023"으로 대체합니다.) 이렇게하려면 Application.Selection.Find를 사용합니다. 새 값이 255자를 초과하면 문제가 발생했습니다 (Microsoft의 제한 사항 ...). 이 문제를 피하기 위해이 경우 TypeText를 사용합니다. 일단 TypeText를 사용하면 교체가 더 이상 작동하지 않습니다. 그리고 나는 이유를 찾을 수 없습니다. 어떤 아이디어라도 대단히 감사하겠습니다.Replace가 TypeText 이후에 작동하지 않습니다.

내 코드를 대체하기 위해 각각의 값을 foreach 문에서 호출 함수에 있습니다

private void Replace(Application app, string name, string newValue) 
{ 
    Selection selection = app.Selection; 
    Find find = selection.Find; 
    Replacement replacement = find.Replacement; 

    find.ClearFormatting(); 
    find.Text = "<" + name + ">"; 

    // Word limitation : can't replace with more than 255 characters, 
    // use another way to do it if that's the case 
    if (tempNewValue.Length < 255) 
    { 
     replacement.ClearFormatting(); 
     replacement.Text = tempNewValue; 
     find.Execute(Replace: replaceAll); 
    } 
    else 
    { 
     while (find.Execute()) 
     { 
      selection.TypeText(tempNewValue); 
     } 
    } 

    Marshal.ReleaseComObject(replacement); 
    Marshal.ReleaseComObject(find); 
    Marshal.ReleaseComObject(selection); 
} 

답변

1

가 나는 문제를 발견했다. 프로그램을 워드로 표시하여 디버그를 실행하는 동안 정확히 무엇을했는지, 왜 작동하지 않는지를 보았습니다.

실제로는 Replace()이 작동했지만 커서 뒤의 발생 만 대체합니다. 이 문제를 해결하려면 커서를 문서의 원점으로 재설정해야합니다.

else 
{ 
    while (find.Execute()) 
    { 
     selection.TypeText(tempNewValue); 
    } 
    selection.GoTo(1, 1); 
}