我需要在Word文件中搜索并查找具有不同背景颜色(突出显示)的所有文本,并将创建的文本写入新的word文件。我怎么能这样做?
我尝试使用此代码:
uses ActiveX, ComObj;
const
wdFindContinue = 1;
wdLine=5;
wdStory = 6;
wdExtend = 1;
wdCharacter = 1;
var
OleObj: Variant;
begin
// create OLE object for MS Word application:
OleObj := CreateOLEObject('Word.Application');
// load a document from your file
OleObj.Documents.Open(YourDocument);
OleObj.Selection.Find.ClearFormatting;
OleObj.Selection.Find.Text := strFinna;
// WordApp.Selection.Find.Replacement.Text := yourNewStringForReplace;
OleObj.Selection.Find.Forward := True;
OleObj.Selection.Find.MatchAllWordForms := False;
OleObj.Selection.Find.MatchCase := False;
OleObj.Selection.Find.MatchWildcards := False;
OleObj.Selection.Find.MatchSoundsLike := False;
OleObj.Selection.Find.MatchWholeWord := False;
OleObj.Selection.Find.MatchFuzzy := False;
OleObj.Selection.Find.Wrap := wdFindContinue;
OleObj.Selection.Find.Format := False;
OleObj.Selection.HomeKey(unit := wdStory);
while OleObj.Selection.Find.Execute do
begin
OleObj.Selection.EndKey(Unit := wdLine, Extend := wdExtend);
OleObj.Selection.MoveRight(Unit := wdCharacter, Count := 1);
OleObj.Selection.MoveUp(Unit := wdLine, Count := 1, Extend := wdExtend);
OleObj.Selection.Delete(Unit := wdCharacter, Count := 1);
end;
OleObj.ActiveDocument.Save;
OleObj.Quit;
OleObj := Unassigned;
end;
是否有任何办公室OLE对象方法的文档?
答案 0 :(得分:1)
下面的代码显示了如何逐个字符地扫描Word文档并报告角色的背景颜色:
procedure TForm1.DoCheckBackground;
var
OleObj: Variant;
YourDocument : String;
Moved : Integer;
Range : OleVariant;
Color : TColor;
begin
YourDocument := 'D:\aaad7\officeauto\parabackground.docx';
// create OLE object for MS Word application:
OleObj := CreateOLEObject('Word.Application');
OleObj.Visible := True;
// load a document from your file
OleObj.Documents.Open(YourDocument);
repeat
Moved := OleObj.Selection.MoveRight(Unit := wdCharacter, Count := 1);
if Moved > 0 then begin
Range := OleObj.Selection.Range;
Color := Range.HighlightColorIndex;
Memo1.Lines.Add(OleObj.Selection.Text + ':' + IntToStr(Color));
end;
until Moved <= 0;
我用一个包含绿色背景的中间段的文档测试了这个,其余的是白色的。代码正确地将HighlightColorIndex报告为中间段为3,其余为0。
供参考,请参阅例如
https://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.selection.moveright.aspx