Ich habe einen Code erstellt, um dies zu erreichen:
Code: Select all
private void formatText() {
Microsoft.Office.Interop.Word.Paragraphs paragraphs = Globals.ThisAddIn.Application.ActiveDocument.Paragraphs;
Boolean isPreviousLineEmpty = false;
Boolean isLastLine = true;
for (int i = paragraphs.Count - 1; i > 0; i--) {
Microsoft.Office.Interop.Word.Paragraph paragraph = paragraphs[i];
if (paragraph.Range.Text.Trim().Equals("")) {
if (isLastLine) {
paragraph.Range.Delete();
continue;
}
if (isPreviousLineEmpty) {
paragraph.Range.Delete(); //This is the line where the error happens
}
isPreviousLineEmpty = true;
continue;
}
if (isLastLine) {
paragraph.Range.Text = paragraph.Range.Text.TrimEnd();
isLastLine = false;
}
isPreviousLineEmpty = false;
}
}
System.Runtime.InteropServices.COMException: „Cannot edit Range.“
Der Grund ist: Es gibt eine weiße Linie im Inhaltsverzeichnis, die mein Code zu entfernen versucht, und das geht nicht. Ich habe die Dokumentation/das Internet durchsucht und alles versucht, was mir einfiel, um zu verhindern, dass mein Code auf TOC-Zeilen ausgeführt wird, aber nichts hat funktioniert.
Ich brauche eine Möglichkeit, um zu wissen, dass ich diese Zeile überspringen kann, weil ich keine Leerzeilen in TOCs löschen muss.
Im Moment kann ich die spezifische Zeile, die den Löschvorgang ausführt, mit einem Try/Catch umschließen blockieren, aber ich denke nicht, dass dies die beste Lösung ist (da ich möglicherweise andere Fehler unbemerkt lasse, dies ist nur ein Schalldämpfer).
Kennt jemand den richtigen Ansatz für diesen Fall?
UPDATE:
Nach dem Freeflow-Kommentar habe ich meinen gesamten Methodencode durch Folgendes ersetzt:
Code: Select all
private void formatText() {
Microsoft.Office.Interop.Word.Find find = Globals.ThisAddIn.Application.ActiveDocument.Range().Find;
Microsoft.Office.Interop.Word.Paragraphs paragraphs = Globals.ThisAddIn.Application.ActiveDocument.Paragraphs;
Boolean operationResult = true;
//Remove blank lines at the end of the document
for (int i = paragraphs.Count - 1; i > 0; i--) {
Microsoft.Office.Interop.Word.Paragraph paragraph = paragraphs[i];
if (paragraph.Range.Text.Trim().Equals("")) {
paragraph.Range.Delete();
continue;
}
paragraph.Range.Text = paragraph.Range.Text.TrimEnd();
break;
}
//Remove blank lines between paragraphs
while (operationResult) {
operationResult = find.Execute("^p^p^p", false, false, false, false, false, false, null, null, "^p^p",
Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
}
}
Vielen Dank für Ihren Kommentar. Wenn Sie es in eine Antwort umwandeln, werde ich es als akzeptiert markieren.
Mobile version